Laravel:hasManyThrough关系

时间:2015-12-21 18:20:30

标签: php mysql laravel

我浪费了一整天但却无法弄清楚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(); }); )但是我无法理解它进行。

以下表格供参考:

import com.google.protobuf.ByteString;

...

GqlQuery.Builder query = GqlQuery.newBuilder().setQueryString(q);
query.addNameArgBuilder()
    .setName("cursor")
    .setCursor(ByteString.EMPTY);

非常感谢任何帮助。谢谢!!!

1 个答案:

答案 0 :(得分: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