I’m having issues with returning belongs to many relationship. Here is my scenario. I have "Individual" model and "Group" model where each individual can belongs to many groups and each group can belongs to many user. Working with database blueprint such as "localhost/phpmyadmin" is fine as I can click at ‘group’ column on "group_individual" table and it returns to the related group on "groups" table. But working inside Laravel, I’m getting empty array. Can you help me please? Thank you for your time.
Migrations
Schema::create('groups', function (Blueprint $table) {
$table->id();
$table->string('group_id')->unique();
$table->string('name');
$table->unsignedBigInteger('members');
$table->string('url')->nullable();
$table->timestamps();
});
Schema::create('individuals', function (Blueprint $table) {
$table->id();
$table->string('search_id')->unique();
$table->timestamps();
});
Schema::create('group_individual',function($table){
$table->id();
$table->string('group');
$table->string('individual');
$table->foreign('group')->references('group_id')->on('groups')->onDelete('cascade');
$table->string('type');
$table->foreign('individual')->references('search_id')->on('individuals')->onDelete('cascade');
});
Individual model
public function groups():IlluminateDatabaseEloquentRelationsBelongsToMany
{
return $this->belongsToMany(Group::class,'group_individual','individual','group');
}
Group model
public function individuals():IlluminateDatabaseEloquentRelationsBelongsToMany
{
return $this->belongsToMany(Individual::class,'group_individual','group','individual');
}
Controller
public function import(){
Individual::create([]);
Group::create([]);
DB::table('group_individual')->insert(['group'=>,'individual'=>,'type'=>]);
$individual=Individual::find(1);
dd($individual->groups);
}
$individual->groups
from above controller returns empty array.
2
Answers
I found solution. I tried to use id of both tables instead of custom other attributes. Here is the code that I use. Instead of using DB::insert() method, I use attach method.
Migrations
Individual Model
Group Model
Controller
Looks like you’ve inverted the ID keys, try switching the ‘group’ and ‘individual’ around in the belongsToMany method