目前我有一个包含两行的简单表:id
和key
。
每当我尝试使用City::get()
从数据库中获取数据时,响应包含字符串格式的id
列。
我是否有一个简单的方法/包如何为每个列定义数据格式?例如。 - 此示例中的id
应为整数。
型号:
<?php
class City extends Eloquent {
protected $table = 'cities';
protected $primaryKey = 'Id';
}
控制器:
class CityController extends \BaseController {
public function index()
{
var_export(is_integer(City::get()->first()->Id));
var_export(is_string(City::get()->first()->Id));
die;
}
}
输出:
false
true
答案 0 :(得分:2)
来自数据库的记录中的每个字段都将是一个字符串。
这就是PHP中有多少db扩展似乎有效。
Ruby on Rails保持模式的常量映射,以便知道tableA.field1是一个整数,因此它可以在获取数据库时将任何内容转换为int。这显然有一些开销,但它可能是一个有用的功能。为了表现而不是方便,Laravel选择不这样做。
您可以使用accessors and mutators手动复制此功能。
答案 1 :(得分:2)
Eloquent Models有一个属性casts
,可用于提示每个模型属性的类型。
这是我使用eloquent来锁定PHP 5.4的遗留应用程序的情况。 由于一些随机的原因,我没有试图找出,每个属性都是从数据库中检索为一个字符串,默认的PHP转换导致我的问题。
您的代码将是:
<?php
class City extends Eloquent {
protected $table = 'cities';
protected $primaryKey = 'Id';
protected $casts = [
'Id' => 'int'
];
}
答案 2 :(得分:0)
您确定数据库中的数据类型也是整数(INT)吗? 或许,您可以将字符串转换为整数。例如:
$num = "4.5";
$int = (int)$num;
return gettype($int); // Integer