简体   繁体   English

向数据透视表Laravel添加值

[英]Add values to pivot table laravel

When I want to save a reaction to a ticket I've three tables (in laravel): 当我想保存对票的反应时,我有三个表(在laravel中):

-Tickets
-Reaction
-Reaction_Tickets (pivot table)

When I want to save a reaction I do it like this: 当我想保存反应时,请按照以下步骤操作:

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.');
    }

But now of course it's not added to the pivot table. 但是,现在当然不会将其添加到数据透视表中。 And I can't add it because I don't have a model of it. 而且我无法添加它,因为我没有它的模型。 What's the right way of doing this? 什么是正确的方法?

EDIT: 编辑:

-Tickets

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

-Reactions

public function tickets()
{
    return $this->hasOne('App\tickets');
}

From the Laravel documentation, you need to save and attach the Reaction to the Ticket : 从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);

In your Ticket model, you need to have the relationship defined: Ticket模型中,需要定义关系:

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

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

And you should have the inverse defined on Reaction : 并且您应该在Reaction定义反函数:

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

    public function tickets(){
        return $this->belongsToMany("App\Ticket"); 
    }
}

If your models are set-up like so, you shouldn't have any issue attaching the new Reaction to your existing Ticket via your pivot table. 如果您的模型是这样设置的,那么通过数据透视表将新的Reaction到现有Ticket上就不会有任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM