Laravel 覆盖的创建方法不';t激发关系()->;创建()
我想通过以下调用向模型添加新标记:Laravel 覆盖的创建方法不';t激发关系()->;创建(),laravel,relationship,laravel-5.1,Laravel,Relationship,Laravel 5.1,我想通过以下调用向模型添加新标记: Modul::find($id)->tags()->create($request->all()); 标记模块中的创建方法是: public static function create(array $attributes = []) { $attributes['user_id'] = Auth::user()->id; return parent::create($attributes); } 但是它说用户id没
Modul::find($id)->tags()->create($request->all());
标记模块中的创建方法是:
public static function create(array $attributes = [])
{
$attributes['user_id'] = Auth::user()->id;
return parent::create($attributes);
}
但是它说用户id没有设置
当我打电话时
Modul::find($id)->tags()->create(array_merge($request->all(), ['user_id' => Auth::user()->id]));
一切正常
我在create函数中进行了一个echo调用,但从未调用过。那么,是否有一个secound create函数我必须覆盖?您调用的
create
方法没有在标记上定义,而是在关系类上定义的。因此,如果您的关系是多对多,那么create
方法就是在类上定义的方法
该方法在内部调用newInstance
model方法。因此,如果您想将用户id
添加到属性中,您可以覆盖该方法,甚至覆盖\u构造函数
,因为这些方法会创建模型的新实例。因此,这应该适用于您的情况:
公共函数newInstance($attributes=[],$exists=false)
{
$attributes['user_id']=Auth::id();
返回父::newInstance($attributes,$exists);
}
这就是说,最好将用户id
作为参数传递,因为否则您会将模型与身份验证系统紧密耦合,并且它可能会产生不可预见的结果,因为该方法也是由Eloquent在内部使用的。您会检查dd(Auth::user()->id)代码>在创建函数中?我做了,但我只是得到一个错误,即没有设置用户id。当我写入$attributes['user\u id']=1
时,它表示未设置user\u id。user\u id
是否添加到$filleble
数组中?是的。正如我所说:当我将用户id与请求数组合并时,一切都正常。但是我想将它添加到create函数中,这样就不必在每次创建调用时进行合并。