laravel hasMany通过一个belongsTo关系 [英] laravel hasManyThrough on a belongsTo relationship

查看:777
本文介绍了laravel hasMany通过一个belongsTo关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



农场 - > hasOne - >地址如下:

  / ** 
* \App\Address与当前场相关联。
*
* @return \App\Address
* /
public function address()
{
return $ this-> hasOne '\App\Address');
}

...然后地址 - > belongsTo - >国家如下: p>

  public function country()
{
return $ this-> belongsTo('\App\国家, 'COUNTRY_ID', 'ID');
}

...我想要检索国家模型并获取所有关联的农场在地址表上使用country_id。我定义了一个hasManyThrough如下:

  / ** 
*获取所有国家的农场。
* /
public function farmms()
{
return $ this-> hasManyThrough('App \Farm','App \Address');
}

但它会生成以下SQL:

  select 
`farms`。*,
`addresses`.`country_id`
from`farms`
inner在`addresses`.`id` =`farms`.`address_id`
中加入`addresses`````````````````` p>

SQL正在农场表中寻找一个address_id。但农场并不属于地址。有没有办法纠正这个或我需要改变我的模式?



非常感谢。

解决方案

为了正常工作,您需要扭转Farm-Address关系的方向:

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

原因是Eloquent假设每个节点在hasManyThrough关系是下一个节点的父类,意味着下一个节点属于上一个节点。在这里,如果要通过地址获得农场,农场需要通过address_id指向地址,并且需要通过country_id指向国家/地区。


I have the following Eloquent relationships where

Farm -> hasOne -> Address as follows :

/**
 * \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. I defined a hasManyThrough as follows:

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

but it generates the following 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. 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:

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. 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.

这篇关于laravel hasMany通过一个belongsTo关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆