【问题标题】:Default Attribute With random Values in laravel modellaravel模型中具有随机值的默认属性
【发布时间】:2021-05-29 01:34:55
【问题描述】:

在我的 laravel 项目中,我想为每个新创建的记录设置一个随机默认值。

根据this Doc,我试试这个:

use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;

class User extends Authenticatable
{
    protected $fillable = [
       'access_token'
    ];

    protected $attributes = [
        'access_token' => str::uuid()
    ];
}

但我收到protected $attributes 行的错误

"Constant expression contains invalid operations"

【问题讨论】:

    标签: php laravel laravel-5.7


    【解决方案1】:

    这是因为属性不能包含在编译时无法计算的表达式。来自官方documentation

    类成员变量称为“属性”。您可能还会看到它们 提及使用其他术语,例如“属性”或“字段”,但 出于本参考的目的,我们将使用“属性”。他们是 使用关键字 public、protected 或 private 之一定义, 然后是一个普通的变量声明。该声明可 包括一个初始化,但这个初始化必须是一个常量 价值——也就是说,它必须能够在编译时被评估,并且 不得依赖运行时信息来进行评估。

    另一种方法是通过model events。在您的 User 模型的 boot() 方法中,您可以挂钩到 Creating 事件。如果此方法不存在,则创建它。

    public static function boot()
    {
        parent::boot();
    
        static::creating(function($user) {
            $user->access_token = (string) Str::uuid();
        });
    }
    

    【讨论】:

      【解决方案2】:
      protected $attributes = [
          'access_token' => ''
      ];
      
      public function __construct(array $attributes = [])
      {
          parent::__construct($attributes);
          $this->attributes['access_token'] = Str::uuid();
      }
      

      在php中,不可能从属性调用函数

      【讨论】:

      • 您好,欢迎来到 StackOverflow!您会考虑添加一些参考资料吗?
      【解决方案3】:

      问题在于您调用 uuid 函数的方式。

      因为它是静态的,所以你需要使用它来访问它;

      Str::uuid()
      

      这将返回一个对象,因此为了从中获取字符串,您必须转换结果。

      (string) Str::uuid()
      

      因此,本质上,您的 attributes 属性应该是;

      protected $attributes = [
          'access_token' => (string) Str::uuid()
      ];
      

      你可以看看docs

      【讨论】:

      • 不,这行不通。类属性不能包含无法在编译时计算的表达式。
      • @Mozammil,你是对的。我想我完全忽略了显而易见的事情,并且按照您的建议,在创建或创建模型事件中使用它会更有意义。谢谢。
      猜你喜欢
      • 2016-02-12
      • 2016-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-15
      • 1970-01-01
      • 2015-12-31
      相关资源
      最近更新 更多