繁体   English   中英

Laravel:有很多关系

[英]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.

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