【问题标题】:Variable type changes after retrieving from Eloquent model in Laravel 5.2从 Laravel 5.2 中的 Eloquent 模型检索后变量类型发生变化
【发布时间】:2016-03-26 14:57:15
【问题描述】:

我在数据库中有名为 marital_status 的表。这仅包含两列 user_id(整数类型)和另一列名为 is_married(布尔类型)。

因此,当我通过 eloquent 模型检索用户的婚姻状况时,我会排除布尔值。

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

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

【问题讨论】:

    标签: php eloquent laravel-5.2


    【解决方案1】:

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

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

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

    【讨论】:

    • 太棒了!这正是我一直在寻找的!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 2016-12-31
    相关资源
    最近更新 更多