2015-12-21 69 views
1

我浪費了整整一天的時間,但無法弄清楚有多少關係。Laravel:hasManyThrough relationship

我有這樣的關係:

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

這產生了我這個查詢:

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' 

一切除了ON funeral_homes_users.id = users.id好應該是ON funeral_homes_users.user_id = users.id。所以我試圖得到的唯一東西是,而不是id,它應該有user_idfuneral_homes_users.id(例如它應該是funeral_homes_users.user_id),但我無法弄清楚。

下面是表以供參考:

// 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(); 
}); 

任何幫助將不勝感激。謝謝 !!!

+2

你確定你有hasManyThrough並沒有太多的一對多的關係? – naneri

+0

@naneri:不知道,我是新來的,我已經發布了表格結構,如果是這種情況,最好有幫助。謝謝 – dev02

+0

我懷疑這是hasManyThrough,因爲'funeral_homes'與用戶沒有直接關係。 – dev02

回答

1

如果我理解正確的話,你的情況是:

USER有許多FUNERAL_HOME

FUNERAL_HOME屬於多個USER

如果這是正確的,你的關係方法應該返回是這樣的:

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'); 
} 

採取看看doku

+0

你是英雄!!!,謝謝你的幫助,真的很感激,你救了我免於浪費另一天:) – dev02

+0

很高興,那可以幫助:) –