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

3 php casting laravel

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

$code = (int)$ratings;
Run Code Online (Sandbox Code Playgroud)

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

Nav*_*Ali 9

我们有一个称为模型的属性cast,您可以在其中指定列名称,如下所示:

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'ratings' => 'integer',
];
Run Code Online (Sandbox Code Playgroud)