Laravels Eloquent ORM: setting datatypes of the mo

2019-07-23 03:31发布

Currently I have a simple table with two rows: id and key.

Whenever I try to get my data from the database with City::get() the response contains id columns in the string format.

Is there a simple way/package how I can define the data formats for each of my columns? E.g. - id in this example should have been an integer.

Model:

<?php
class City extends Eloquent {

    protected $table = 'cities';
    protected $primaryKey = 'Id';

}

Controller:

class CityController extends \BaseController {

    public function index()
    {
        var_export(is_integer(City::get()->first()->Id));
        var_export(is_string(City::get()->first()->Id));
        die;
    }

}

Output:

false
true

3条回答
The star\"
2楼-- · 2019-07-23 03:55

Every field from a record that comes out of the database is going to be a string.

This is just how many db extensions in PHP seem to work.

Ruby on Rails keeps a constant map of the schema to know that tableA.field1 is an integer, so it can convert anything to an int when it fetches the database. This obviously has some overhead to it, but it can be a useful feature. Laravel opted to not do this in the interest of performance over convenience.

You can use accessors and mutators to manually replicate this functionality.

查看更多
一纸荒年 Trace。
3楼-- · 2019-07-23 04:14

Are you sure that the data type in the database is an integer (INT) as well? Else you could, maybe, convert the string to an integer. For example:

$num = "4.5";
$int = (int)$num;

return gettype($int); // Integer
查看更多
贪生不怕死
4楼-- · 2019-07-23 04:20

Eloquent Models have a property casts that can be used to hint at the type for each model attribute.

This was my case using eloquent for a legacy application locked to PHP 5.4. For some random reason i didn't try to figure out, every attribute was retrieved as a string from the database and the default PHP casting was causing me problems.

Your code would be:

<?php
class City extends Eloquent {
    protected $table = 'cities';
    protected $primaryKey = 'Id';
    protected $casts = [
        'Id' => 'int'
    ];
}
查看更多
登录 后发表回答