简体   繁体   English

laravel hassManyThrough on属于归属关系

[英]laravel hasManyThrough on a belongsTo relationship

I have the following Eloquent relationships where 我有以下雄辩的关系,其中

Farm -> hasOne -> Address as follows : 农场-> hasOne->地址如下:

/**
 * \App\Address associated to the current farm.
 *
 * @return \App\Address
 */
public function address()
{
    return $this->hasOne('\App\Address');
} 

...then Address -> belongsTo -> Country as follows: ...然后地址->属于->国家,如下所示:

public function country()
{
    return $this->belongsTo('\App\Country','country_id','id');
}

... and I'm like to retrieve the Country model and get all associated farms using the country_id on the address table. ...,我想使用国家/地区地址表上的country_id检索Country模型并获取所有关联的农场。 I defined a hasManyThrough as follows: 我定义了一个hasManyThrough,如下所示:

/**
 * Get all of the farms for the country.
 */
public function farms()
{
    return $this->hasManyThrough('App\Farm', 'App\Address');
}

but it generates the following SQL: 但它生成以下SQL:

select 
    `farms`.*, 
    `addresses`.`country_id` 
from `farms` 
inner join `addresses` on `addresses`.`id` = `farms`.`address_id` 
where `addresses`.`country_id` = 1

The SQL is looking for an address_id on the farms table. SQL在场表中查找address_id。 But the farm does not "belongTo" an address. 但是服务器场不“属于”地址。 Is there anyway to correct this or am I stuck needing a change to my schema? 无论如何,有没有要解决的问题,还是我需要更改架构?

Many thanks. 非常感谢。

In order for that to work you'll need to reverse the direction of Farm-Address relation: 为了使它起作用,您需要反转Farm-Address关系的方向:

class Farm extends Model {
  public function address() {
    return $this->belongsTo(Address::class);
  }
}

The reason is that Eloquent assumes that every "node" in hasManyThrough relation is kind of a parent for the next node, meaning the next node belongs to the previous node. 原因是Eloquent假设hasManyThrough关系中的每个“节点”都是下一个节点的父级,这意味着下一个节点属于前一个节点。 Here if you want to get farms through address for given country, farm needs to point to address via address_id and address needs to point to country via country_id. 在这里,如果要通过给定国家/地区的地址获取服务器场,则服务器场需要通过address_id指向地址,而地址则需要通过country_id指向国家/地区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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