问题
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
回答1:
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.
回答2:
Eloquent Models have a property casts
that can be used to hint at the type for each model attribute.
- 5.0: https://laravel.com/docs/5.0/eloquent#attribute-casting
- 5.4: https://laravel.com/docs/5.4/eloquent-mutators#attribute-casting
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'
];
}
回答3:
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
来源:https://stackoverflow.com/questions/24528062/laravels-eloquent-orm-setting-datatypes-of-the-model