简体   繁体   中英

Laravel: hasManyThrough relationship

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 !!!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM