首先抱歉我的英語不好。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
]
add'dd($ ticket)'here – mcklayin
我不能'dd($ ticket)'。因爲錯誤發生在'$ ticket = ....'行中。 –
如果TicketReply'belongsTo(User :: class)',應該不是User'hasMany - >(TicketReply :: class)'? –