当我想保存对票的反应时,我有三张桌子(在laravel中):
-Tickets
-Reaction
-Reaction_Tickets (pivot table)
当我想保存反应时,我这样做:
public function addReaction(Request $request, $slug)
{
$ticket = Ticket::whereSlug($slug)->firstOrFail();
$reaction = new reactions(array(
'user_id' => Auth::user()->id,
'content' => $request->get('content')
));
return redirect('/ticket/'.$slug)->with('Reactie is toegevoegd.');
}
但是现在它当然没有添加到数据透视表中。我无法添加它,因为我没有它的模型。这样做的正确方法是什么?
编辑:
-Tickets
public function reactions()
{
return $this->belongsToMany('App\reactions');
}
-Reactions
public function tickets()
{
return $this->hasOne('App\tickets');
}
答案 0 :(得分:5)
从Laravel文档中,您需要将Reaction
保存并附加到Ticket
:
$reaction = new reactions(array(
'user_id' => Auth::user()->id,
'content' => $request->get('content')
));
$reaction->save(); // Now has an ID
$tickets->reactions()->attach($reaction->id);
在Ticket
模型中,您需要定义关系:
class Ticket extends Model {
protected $table = "tickets";
public function reactions(){
return $this->belongsToMany("App\Reaction");
}
}
你应该在Reaction
上定义反向:
class Reaction extends Model {
protected $table = "reactions";
public function tickets(){
return $this->belongsToMany("App\Ticket");
}
}
如果您的模型设置如此,那么您通过数据透视表将新Reaction
附加到现有Ticket
时不会有任何问题。