从Laravel 5.2中的Eloquent模型检索后变量类型发生变化


Variable type changes after retrieving from Eloquent model in Laravel 5.2

我在数据库中有一个名为marital_status的表。这只包含两列user_id(Integer类型)和另一列is_married(boolean类型)。

所以,当我通过雄辩模型检索用户的婚姻状况时,我会排除布尔值。

   Auth::user()->maritalStatus // equals always string not boolean.

结果是正确的,但我得到的不是布尔值,而是字符串"0"或"1"。有人能解释一下吗?

您可以在模型中解决此问题:

protected $casts = [
    'is_married' => 'boolean'
];

https://laravel.com/docs/5.2/eloquent-mutators#attribute-铸造