I'm trying to insert a belongsTo to my pivot table. I have a comments and documents table that has a One to many relationship and comments and users table that has a many to many relationship. The pivot table is comment_user.
I can insert the belongsTo relationship but I'm having a problem where I need to insert the comments id together with the users id(Current user). See my relationship below.
Database Diagram
Models:
Comment
class Comment extends Model
{
protected $tables = 'comments';
protected $fillable =
[
'comment',
'document_id',
];
public function users()
{
return $this->belongsToMany('App\Models\User', 'comment_user', 'comment_id', 'user_id');
}
public function documents()
{
return $this->belongsTo('App\Models\Document');
}
}
User:
class User extends Model implements AuthenticatableContract
{
use Authenticatable;
protected $table = 'users';
protected $fillable = [
'first_name',
'last_name',
'middle_name',
'email',
'username',
'address',
'password',
'role_permission_id',
];
public function comments()
{
return $this->belongsToMany('App\Models\Comment', 'comment_user', 'user_id', 'comment_id');
}
}
Controller:
class CommentController extends Controller
{
public function postComments(Request $request, Document $id)
{
$this->validate($request,
[
'comment' => 'required',
]);
$commentObject = new Comment();
$user = Auth::user();
$commentObject->comment = $request->comment;
$id->comments()->save($commentObject);
$commentObject->users()->sync(['comment_id' => $commentObject, 'user_id' => $user->id],false);
return redirect()->back();
}
}
Problem
I just wanted to insert the id of Model Comment and also the current user. I tried this but it says.
$commentObject->users()->sync(['user_id' => $user->id],false);
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
webdev.comment_user, CONSTRAINTcomment_user_sender_id_foreignFOREIGN KEY (sender_id) REFERENCESusers(id) ON DELETE CASCADE) (SQL: insert intocomment_user(comment_id,user_id) values (36, 11))
As you can see here the 36 is the current id of Comment and the 11 is the current id of logged in user. Any help how can I achieve this?

create table ...to your question so we can check the constraints. - u-nik$user->comments()should be of typehasMany(). A user has Many comments, and a comment belongs To a user. You should do it this way, it'll all become simpler. - Steve Chamaillard