【发布时间】:2023-03-08 18:21:02
【问题描述】:
我有以下 Eloquent 关系,其中
Farm -> hasOne -> 地址如下:
/**
* \App\Address associated to the current farm.
*
* @return \App\Address
*/
public function address()
{
return $this->hasOne('\App\Address');
}
...然后地址 -> 属于 -> 国家如下:
public function country()
{
return $this->belongsTo('\App\Country','country_id','id');
}
...我想检索 Country 模型并使用地址表上的 country_id 获取所有关联的农场。我定义了一个 hasManyThrough 如下:
/**
* Get all of the farms for the country.
*/
public function farms()
{
return $this->hasManyThrough('App\Farm', 'App\Address');
}
但它会生成以下 SQL:
select
`farms`.*,
`addresses`.`country_id`
from `farms`
inner join `addresses` on `addresses`.`id` = `farms`.`address_id`
where `addresses`.`country_id` = 1
SQL 正在农场表中查找 address_id。但是农场不“属于”一个地址。无论如何要纠正这个问题还是我需要更改我的架构?
非常感谢。
【问题讨论】:
-
请告诉我们生成的sql的模型和来源。
-
更新了问题以包括模型关系,在底部生成 SQL。感谢您的帮助。
标签: php laravel laravel-5 eloquent