[英]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
,它應該具有用於funeral_homes_users.id
user_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();
});
任何幫助將不勝感激。 謝謝 !!!
如果我正確理解,您的情況是:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.