everyone, i have table statuses with fields id
, user_id
, parent_id
, body
.
now the status table has relations with user like this :
Status Model
public function user() {
return $this->belongsTo('App\User', 'user_id');
}
public function scopeNotReply($query) {
return $query->whereNull('parent_id');
}
public function replies() {
return $this->hasMany('App\Status', 'parent_id');
}
User Model
public function statuses() {
return $this->hasMany('App\Status', 'user_id');
}
but, unfortunately i can't access the user_id
when i want to reply the status and save into database with same table statuses
. I use the associate
method and the StatusController is like this :
public function postReply(Request $request, $statusId){
$this->validate($request, [
"reply-{$statusId}" => 'required|max:1000',
]);
$status = Status::notReply()->find($statusId)->first();
$reply = Status::create([
'body' => $request->input("reply-{$statusId}"),
])->user()->associate(Auth::user());
$status->replies()->save($reply);
return redirect()->back();
}
everytime i try to reply the status, i got this error message SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value
.
Could anybody to help me to solve this problem ??
Thank You
The reason you're getting this error is because you're creating the Status
before the user_id
has been associated with it.
One way to get around this would be to move the user_id
logic inside the create array ie:
Status::create([
'body' => $request->input("reply-{$statusId}"),
'user_id' => Auth:user()->id
]);
Hope this helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.