2015-12-21 71 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

很高兴,那可以帮助:) –