I need to create a many to many relationship from the users table to the same table. That is to say that it has the relationship towards itself. When trying to put the relationship with laravel attach.
$usuario_seguido->user_user()->attach($usuario);
This gives me this error.
Illuminate/Database/QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field 'user_id_seguido' doesn't have a default value (SQL: insert into `user_user` (`user_id`) values (2))'
This is the relationship in the User model.
public function user_user()
{
return $this->belongsToMany(User::class,'user_user')->withPivot('user_id','user_id_seguido');;
}
This is the pivot table
public function up()
{
Schema::create('user_user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('user_id_seguido');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('user_id_seguido')->references('id')->on('users');
});
}
You will have to explicitly declare the foreign keys of the pivot table.
I changed the name of the relation to something more descriptive, so it's easier to read for you and other programmers.
And to declare the inverse relationship:
Then you can relate the users:
And get the results: