如何在 Laravel 模型中将 String 转换为 int

这是我的解决方案。我在模型类中写了这个。(评分是字符串类型)

$code = (int)$ratings;

但我需要在从数据库检索 $ ratings 时更改它。我该怎么做?


湖上湖
浏览 162回答 4
4回答

潇湘沐

我们有一个名为的模型属性cast,您可以在其中指定列名称,如下所示:/** * The attributes that should be cast to native types. * * @var array */protected $casts = [    'ratings' => 'integer',];

LEATH

来自 Laravel 文档:属性转换 模型上的 $casts 属性提供了一种将属性转换为通用数据类型的便捷方法。$casts 属性应该是一个数组,其中键是要转换的属性的名称,值是您希望将列转换为的类型。支持的转换类型包括整型、实型、浮点型、双精度型、小数型、字符串型、布尔型、对象型、数组型、集合型、日期型、日期时间型和时间戳型。转换为十进制时,必须定义位数(十进制:2)。<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class User extends Model{    /**     * The attributes that should be cast.     *     * @var array     */    protected $casts = [        'ratings' => 'integer',    ];}为 null 的属性将不会被强制转换。此外,您永远不应该定义与关系同名的强制转换(或属性)。

jeck猫

尝试这个:protected $casts = ['ratings' => 'integer'];

阿晨1998

您可以通过向模型添加protected $casts&nbsp;int来在 Eloquent 中转换属性:protected&nbsp;$casts&nbsp;=&nbsp;[ &nbsp;&nbsp;&nbsp;&nbsp;'ratings'&nbsp;=>&nbsp;'integer', ];这使用 return&nbsp;(int)&nbsp;$value将您的字段转换为整数。
打开App,查看更多内容
随时随地看视频慕课网APP