向数据透视表laravel添加值

Jam*_*mie 2 php pivot laravel

当我想保存对票的反应时,我有三张桌子(在laravel中):

-Tickets
-Reaction
-Reaction_Tickets (pivot table)
Run Code Online (Sandbox Code Playgroud)

当我想保存反应时,我这样做:

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.');
    }
Run Code Online (Sandbox Code Playgroud)

但是现在它当然没有添加到数据透视表中.我无法添加它,因为我没有它的模型.这样做的正确方法是什么?

编辑:

-Tickets

public function reactions()
{
    return $this->belongsToMany('App\reactions');
}

-Reactions

public function tickets()
{
    return $this->hasOne('App\tickets');
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*wis 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);
Run Code Online (Sandbox Code Playgroud)

在您的Ticket模型中,您需要定义关系:

class Ticket extends Model {
    protected $table = "tickets";

    public function reactions(){
        return $this->belongsToMany("App\Reaction"); 
    }
}
Run Code Online (Sandbox Code Playgroud)

你应该定义逆定义Reaction:

class Reaction extends Model {
    protected $table = "reactions";

    public function tickets(){
        return $this->belongsToMany("App\Ticket"); 
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您的模型设置如此,那么您应该通过数据透视表将新内容附加Reaction到现有模型Ticket中.