gpt4 book ai didi

php - Laravel: hasManyThrough 关系

转载 作者:行者123 更新时间:2023-11-28 23:41:01 25 4
gpt4 key购买 nike

我浪费了一整天的时间,但无法弄清楚 hasManyThrough 关系。

我有这样的关系:

# 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_id 用于 funeral_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();
});

如有任何帮助,我们将不胜感激。谢谢!!!

最佳答案

如果我没理解错的话,你的情况是:

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

关于php - Laravel: hasManyThrough 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34401997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com