2017-03-16 175 views
0

首先抱歉我的英語不好。Laravel user_id在多對多的關係


我有三個簡單的模型:

用戶

class User extends Authenticatable 
{ 
    protected $fillable = [ 
     'first_name', 'last_name' 
    ]; 

    public function tickets() 
    { 
     return $this->hasMany(Ticket::class); 
    } 

} 

票務

class Ticket extends Model 
{ 
    protected $fillable = ['user_id', 'title']; 

    public function user() 
    { 
     return $this->belongsTo(User::class); 
    } 

    public function replies() 
    { 
     return $this->hasMany(TicketReply::class); 
    } 
} 

TicketReply

class TicketReply extends Model 
{ 

    protected $fillable = ['user_id', 'ticket_id', 'text']; 

    public function user() 
    { 
     return $this->belongsTo(User::class); 
    } 

    public function ticket() 
    { 
     return $this->belongsTo(Ticket::class); 
    } 
} 

所以,要創建一個新的票據,它需要創建一個票據和一個答覆。

我用下面的方法TicketController用於創建新票價:

public function createNewTicket(Request $request) 
{ 
    $ticket = $request->user()->tickets()->create($request->all()); 
    $replies = $ticket->replies()->create($request->all()); // Error occurs in this line 
} 

但它返回此錯誤:

SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "user_id" violates not-null constraint ...

的問題是:

爲什麼Laravel沒有按不承認TicketReply的擁有者?!

我希望我已經解釋清楚了。

PS:

注意$request的數據是這樣的:

array:2 [▼ 
    "title" => "My Ticket Title" // `title` field of Ticket Model 
    "text" => "Ticket Text Goes Here" // `text` field of TicketReply Model 
] 
+0

add'dd($ ticket)'here – mcklayin

+0

我不能'dd($ ticket)'。因爲錯誤發生在'$ ticket = ....'行中。 –

+0

如果TicketReply'belongsTo(User :: class)',應該不是User'hasMany - >(TicketReply :: class)'? –

回答

0

我認爲你不能設置用戶ID上創建重播票作爲模型只有一個foregin鍵,你可以這樣做:

$replies = $ticket->replies()->create($request->all() + ['user_id' => $request->user()->id]); 
+0

當我嘗試爲'Ticket'創建新的TicketReply時發生錯誤。 –

+0

不,這不是正確的答案 –

0

我們認爲正確的解決方案是手動指定用戶ID和票。 祝你好運!

0

Laravel無法知道它。它只知道其中一個字段是ticket上的user_id,但它不知道你想使用它。此外,它看起來像那種關係的代碼不是100%正確的設計。

你想要的是:

user has many tickets 
user has many ticketreplies 
ticket belongs to user 
ticket has many ticketreplies 
ticketreply belongs to ticket 
ticketreply has many users 

然後創建一個像你這樣的票,

創建ticketReply這樣的:

$fields = $request->all(); 
$fields['user_id'] = $request->user()->id; 
$ticket->replies()->create($fields); 

還有其他的方法爲好,即

$fields = $request->all(); 
$fields->user_id = $request->user()->id; 
$fields->ticket_id = $ticket->id; 
$ticketReply = \App\TicketReply::create($fields);