具有此模型:
class Subject extends BaseEntity implements Treeable
{
use NodeTrait;
protected $table = 'subjects';
protected $rules = [
'label' => 'max:255',
'parent_id' => 'exists:subjects,id' // <--
];
protected function getScopeAttributes()
{
return [ 'user_id' ];
}
}
然后我创建一个新实例(parent_id引用同一表的ID,并且ID 3存在):
Subject::create([
'label' => 'foo',
'parent_id' => 3
])
这将导致两个查询:
select count(*) as aggregate from subjects where id = 3
(得到预期结果1)
select * from subjects where subjects.user_id is null and subjects.id = 3
(空结果抛出No query results for model [App\\Subject] 3
异常)
我发现,由于范围的原因,添加了附加的subjects.user_id is null
,但是如何将其添加到验证中呢?要么在创建时的有效负载中以任何方式删除或设置它,要么使用auth()->id
动态地对其进行设置。有人可以帮忙吗?
答案 0 :(得分:1)
好,知道了。并不是专门用于验证,我必须在“ parent_id”之前添加“ user_id”作为参数,就像这样:
url_stat
答案 1 :(得分:0)
在此处输入代码
您应该使用启动功能自动创建和更新。
public static function boot()
{
parent::boot();
// create a event to happen on updating
static::updating(function($table) {
$table->user_id = Auth::user()->id;
});
// create a event to happen on saving
static::saving(function($table) {
$table->user_id = Auth::user()->id;
});
}