Laravel: hasManyThrough relationship

- 1 answer

Ad

I wasted my whole day but cannot figure out hasManyThrough relationship.

I have this relationship:

# get related users
public function users()
{
    return $this->hasManyThrough(User::class, FuneralHomeUser::class, 'user_id', 'id');
}

This generates me this query:

SELECT `users`.*, `funeral_homes_users`.`user_id`
FROM `users`
INNER JOIN `funeral_homes_users` ON `funeral_homes_users`.`id` = `users`.`id`
WHERE `funeral_homes_users`.`user_id` = '4'

Everything is good except for ON funeral_homes_users.id = users.id should be ON funeral_homes_users.user_id = users.id. So the only thing I am trying to get is instead of id, it should have user_id for funeral_homes_users.id (eg it should be funeral_homes_users.user_id) but I am unable to figure it out.

Here are tables for reference:

// funeral_homes
Schema::create('funeral_homes', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name', 255);
    $table->timestamps();
});

// funeral_homes_users
Schema::create('funeral_homes_users', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('funeral_home_id')->unsigned();
    $table->integer('user_id')->unsigned();
    $table->timestamps();
});

// users
Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('email')->unique();
    $table->string('password', 60);
    $table->rememberToken();
    $table->string('first_name');
    $table->string('last_name');
    $table->timestamps();
});

Any help would be greatly appreciated. Thanks !!!

Ad

Answer

Ad

If I understand it correctly, your case is:

USER has many FUNERAL_HOME

FUNERAL_HOME belongs to many USER

if that is correct, your relation methods should return something like this:

User.php

public function FuneralHomes()
{
    return $this->belongsToMany(FuneralHome::class, 'funeral_homes_users');
}

FuneralHome.php

public function Users()
{
    return $this->belongsToMany(User::class, 'funeral_homes_users');
}

Take look at the doku

Ad
source: stackoverflow.com
Ad