Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 拉威尔对一段属于自己的感情有很多想法_Php_Laravel_Laravel 5_Eloquent - Fatal编程技术网

Php 拉威尔对一段属于自己的感情有很多想法

Php 拉威尔对一段属于自己的感情有很多想法,php,laravel,laravel-5,eloquent,Php,Laravel,Laravel 5,Eloquent,我有以下雄辩的关系 农场->哈桑->地址如下: /** * \App\Address associated to the current farm. * * @return \App\Address */ public function address() { return $this->hasOne('\App\Address'); } …然后地址->归属->国家,如下所示: public function country() { return $this-&

我有以下雄辩的关系

农场->哈桑->地址如下:

/**
 * \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');
}
/**
 * Get all of the farms for the country.
 */
public function farms()
{
    return $this->hasManyThrough('App\Farm', 'App\Address');
}
。。。我想检索国家模型,并使用地址表上的国家id获取所有相关农场。我对hasManyThrough的定义如下:

public function country()
{
    return $this->belongsTo('\App\Country','country_id','id');
}
/**
 * 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正在farms表中查找地址\u id。但是农场没有“属于”一个地址。是否有任何方法可以纠正这一点,或者我是否需要更改我的模式


非常感谢。

要使其发挥作用,您需要反转场地址关系的方向:

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

原因是Elount假设hasManyThrough关系中的每个“节点”都是下一个节点的父节点,这意味着下一个节点属于上一个节点。这里,如果您想通过给定国家/地区的地址获取农场,农场需要通过地址id指向地址,而地址需要通过国家/地区id指向国家/地区。

为了实现这一点,您需要颠倒农场地址关系的方向:

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

原因是Elount假设hasManyThrough关系中的每个“节点”都是下一个节点的父节点,这意味着下一个节点属于上一个节点。这里,如果您想通过给定国家/地区的地址获取农场,农场需要通过地址id指向地址,而地址需要通过国家/地区id指向国家/地区。

请向我们展示生成的sql的模型和来源。更新问题以包括模型关系,在底部生成sql。感谢您的帮助。请向我们展示模型和生成的sql的来源。已更新问题以包括模型关系,底部为生成的sql。谢谢你的帮助。