0

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

用户表:

在此处输入图像描述

门票表:

在此处输入图像描述

ticket_cc_users 表:

在此处输入图像描述

现在,我已经创建了用户和票证模块之间的关系,如下所示。

用户型号:

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]: Column not found: 1054 Unknown column '$$hashKey' in 'field list' (SQL: insert into ticket_cc_users( $$hashKey, address, city_id, country_id, created_at, deleted_at, email, firstname, id, introducer_id, is_verified, lastname, phone, signature, state_id, ticket_id, updated_at, user_id, username, userrole_id) 值 (object:109, , , , 2017-02-10 05:26:01, , nisarg.b@infirays.com, , 26, 1, , , 9999999999, , , 1, 2017-02 -14 08:33:18, 0, 尼萨尔, 2))

那么,我应该在保存功能中更改哪些代码才能将数据存储到ticket_cc_users表中?

4

1 回答 1

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 多到多文档

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

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

于 2017-02-22T09:00:45.373 回答