Max*_*cot 1 php laravel eloquent
在我的 Laravel 应用程序中,一个简单的 eloquent 调用会为我表中的新项目生成一个新 id。 $Article = new Article;
如果我还想同时生成自定义代码,我该怎么做?
我试过这个:
protected $fillable = [
'RandomReference' => substr(md5(rand()), 0, 7),
...
Run Code Online (Sandbox Code Playgroud)
但得到这个错误: Constant expression contains invalid operations
如果我将其设为受保护的字段(而不是可填写的)也无济于事。
该fillable属性需要一个属性名称列表。您将无法通过任何动态调用来为这些属性生成数据。
您可以使用该boot方法在创建事件时自动生成属性。
protected $fillable = [
'RandomReference', /* ... */
];
public static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->RandomReference = substr(md5(rand()), 0, 7);
});
}
Run Code Online (Sandbox Code Playgroud)
有关更多示例,请参阅此参考资料。
| 归档时间: |
|
| 查看次数: |
4042 次 |
| 最近记录: |