在Laravel5.4中将数据插入数据透视表

时间:2017-02-22 07:28:56

标签: mysql laravel-5.4 laravel-eloquent

我在Laravel5.4工作。我创建了3个表格。

用户表:

enter image description here

门票表:

enter image description here

ticket_cc_users表:

enter image description here

现在,我已经在用户和故障单模块之间建立关系,如下所示。

用户模型:

public function tickets()
{
    return $this->belongsToMany('App\User', 'ticket_cc_users', 'user_id', 'ticket_id');
}

故障单型号:

public function users()
{
    return $this->belongsToMany('App\Models\Tickets\Ticket', 'ticket_cc_users', 'ticket_id', 'user_id');
}

TicketController控制器保存方法:

public function store(Request $request)
{
    return $request->all();
    $ticket = new Ticket;
    $ticket->requester_id = $this->user['id'];
    //$ticket->assignee_id = $request->assignee_id;
    //$ticket->cc_id = $request->cc_id;
    $ticket->type = $request->type;
    $ticket->priority = $request->priority;
    $ticket->subject = $request->subject;
    $ticket->description = $request->description;
    $ticket->status = $request->status;
    if($request->link)
    {
        $ticket->link = $request->link;
        $ticket->due_date = null;
    }
    if($request->due_date && $request->due_date !="")
    {
        $ticket->due_date = date('Y-m-d',strtotime($request->due_date));
        $ticket->link = "";
    }
    if($ticket->save())
    {
        $ticket->users()->sync($request->cc_id);

        foreach($request->ticket_tags as $value){
            $tag = new Tag;
            $tag->tag_name = $value['text'];
            $tag->save();
            $ticketTag = new TicketTag;
            $ticketTag->tickets_id = $ticket->id;
            $ticketTag->tags_id = $tag->id;
            $ticketTag->save();
        }

        $data = Ticket::find($ticket->id);
        Mail::to('khyati@infirays.com')->send(new CreateTicket($data));

        $response = array(
            'success' => true
        );
    }
    return $response;
}

在这里,我要将数据存储到票证表中。所以我需要将cc用户数据存储到ticket_cc_user表中。那么如何将ticket_id和user_id存储到此表中。在这里,我可以获得多个user_id。我正在使用Eloquent ORM。

这里,它给出了一个错误,如 SQLSTATE [42S22]:未找到列:1054未知列' $$ hashKey'在'字段列表' (SQL:插入ticket_cc_users$$hashKeyaddresscity_idcountry_idcreated_atdeleted_at,{{1 }},emailfirstnameidintroducer_idis_verifiedlastnamephonesignaturestate_idticket_idupdated_atuser_idusername)值(对象:109 ,,,,,2017-02-10 05:26:01 ,, nisarg.b @ infrays.com ,, 26,1,,9999999999 ,,,,2017-02-14 08:33:18,0,nisarg,2))

那么,我应该在save函数中更改哪些代码来将数据存储到userrole_id表中?

1 个答案:

答案 0 :(得分:0)

似乎应该更改belongsToMany()参数顺序。第一个和最后一个(第4个)参数应该是"关于"同样的例子。

更新还应交换tickets()users()函数的正文

所以试试这个:

用户模型:

public function tickets()
{
    return $this->belongsToMany('App\Models\Tickets\Ticket', 'ticket_cc_users', 'user_id', 'ticket_id');
}

故障单型号:

public function users()
{
return $this->belongsToMany('App\User', 'ticket_cc_users', 'ticket_id', 'user_id');        
}

来自Laravel Many To Many Docs

  

第三个参数是您定义关系的模型的外键名称,而第四个参数是您要加入的模型的外键名称:

     

返回$ this-> belongsToMany(' App \ Role',' role_user',' user_id',' role_id');