如何将 Laravel Eloquent 里的数值属性强制转换为布尔类型?

Laravel

I wanted to return a value that gets saved as an integer in the 'active' column in a database table as a boolean.

My initial ugly solution was to change the attribute like this (that is to force the return type to boolean):

public function getActiveAttribute($value): bool
{
       return $value;
}

My code reviewer found a much better solution:

https://learnku.com/docs/laravel/6.x/eloquent-muta...

So I replaced above code in the Eloquent model with this:

 protected $casts = [
        'active' => 'boolean',
    ];
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://dev.to/programmingdecoded/castin...

译文地址:https://learnku.com/laravel/t/41713

本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!