向数据透视表laravel

时间:2015-10-23 17:43:35

标签: php laravel pivot

当我想保存对票的反应时,我有三张桌子(在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');
}

1 个答案:

答案 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时不会有任何问题。