ow and i'm running laravel 5.7.29 and php 7.2
Feb 28, 2020
19
Level 1
Many to many relationship not working. Can anyone help?
Hello i have been trying to create a many to many relationship. but it does not work.
I have 2 models User and Competency
and 2 tables Users and Competenties
First i created a migration for the pivot table:
public function up()
{
Schema::create('competency_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('competency_id')->unsigned();
$table->foreign('competency_id')->references('id')->on('competencies');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
}
Than i added the BelongsToMany to the classes:
class User extends Authenticatable
{
use HasApiTokens, Notifiable, SoftDeletes;
protected $casts = [
'created_at' => 'datetime',
'updated_at' => 'datetime',
'is_admin' => 'bool',
'is_super_admin' => 'bool'
];
protected $fillable = [
'name', 'email', 'password', 'team_id'
];
protected $hidden = [
'password', 'remember_token', 'is_admin', 'is_super_admin'
];
.....
.....
public function competencies()
{
return $this->belongsToMany(Competency::class,'competency_user','competency_id','user_id');
}
class Competency extends Model
{
use SoftDeletes;
protected $casts = [
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
protected $fillable = [
'name', 'description', 'icon', 'competency_set_id', 'card_image_da_id', 'order_value'
];
...
...
public function Users()
{
return $this->belongsToMany(User::class,'competency_user','user_id','competency_id');
}
}
But when i test i out i get null
or not an error at all:
$user = User::find(1);
dd($user->competencies()->toSql());
]8;;file:///Users/maj/Documents/code/sites/api/tests/Feature/ClientUpdateProfileTest.php#L133\^]8;;\ "select * from `competencies` inner join `competency_user` on `competencies`.`id` = `competency_user`.`user_id` where `competency_user`.`competency_id` = ? and `competencies`.`deleted_at` is null"
this should be something like (this works in the database)
SELECT *
FROM `competencies` c
INNER JOIN `competency_user` cu ON c.`id` = cu.`competency_id`
INNER JOIN `users` u ON cu.`user_id` = u.`id`
$user = User::find(1);
dd($user->competencies()->attach(4));
give null
can anyone help me out?
Level 102
It seems you have your column names reversed
public function competencies()
{
return $this->belongsToMany(Competency::class,'competency_user','user_id','competency_id');
}
1 like
Please or to participate in this conversation.