为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
湖上湖 2023-10-15 17:30:33
这是我的解决方案。我在模型类中写了这个。(评分是字符串类型)$code = (int)$ratings;但我需要在从数据库检索 $ ratings 时更改它。我该怎么做?
查看完整描述

4 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

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


/**

 * The attributes that should be cast to native types.

 *

 * @var array

 */

protected $casts = [

    'ratings' => 'integer',

];


查看完整回答
反对 回复 2023-10-15
?
LEATH

TA贡献1936条经验 获得超6个赞

来自 Laravel 文档:

属性转换 模型上的 $casts 属性提供了一种将属性转换为通用数据类型的便捷方法。$casts 属性应该是一个数组,其中键是要转换的属性的名称,值是您希望将列转换为的类型。支持的转换类型包括整型、实型、浮点型、双精度型、小数型、字符串型、布尔型、对象型、数组型、集合型、日期型、日期时间型和时间戳型。转换为十进制时,必须定义位数(十进制:2)。

<?php


namespace App;


use Illuminate\Database\Eloquent\Model;


class User extends Model

{

    /**

     * The attributes that should be cast.

     *

     * @var array

     */

    protected $casts = [

        'ratings' => 'integer',

    ];

}

为 null 的属性将不会被强制转换。此外,您永远不应该定义与关系同名的强制转换(或属性)。


查看完整回答
反对 回复 2023-10-15
?
jeck猫

TA贡献1909条经验 获得超7个赞

尝试这个:


protected $casts = [

'ratings' => 'integer'

];


查看完整回答
反对 回复 2023-10-15
?
阿晨1998

TA贡献2037条经验 获得超6个赞

您可以通过向模型添加protected $casts int来在 Eloquent 中转换属性:

protected $casts = [
    'ratings' => 'integer',
];

这使用 return (int) $value将您的字段转换为整数。


查看完整回答
反对 回复 2023-10-15
  • 4 回答
  • 0 关注
  • 99 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信