返回 wrong/null 数据的关系 (Laravel 5.2)

Relationships returning wrong/null data (Laravel 5.2)

得到了一个 domain table,它有一个 One To Many relationship 以及 domain_hosts_tableserver_hosts_tablesystems_table。到目前为止一切顺利。

正在调用 table 数据:

$domains = Domain::with('domain_host', 'server_host', 'system')->get();

领域 模型:

public function domain_host()
{
    return $this->hasOne('App\DomainHost', 'id');
}

public function server_host()
{
    return $this->hasOne('App\ServerHost', 'id');
}

public function system()
{
    return $this->hasOne('App\System', 'id');
}

DomainHostServerHostSystem 型号:

public function domains()
{
    return $this->hasMany('App\Domain');
}

table :

到目前为止一切顺利。

让我们来看看这个tablereturns在foreached.

前 2 行应该相同(基于它们的 ID),前 2 行之后的所有行都是空的。

(获取数据的dd,注意第4个对象的关系是空的,第1个对象实际上有数据)。

定义我的关系时必须定义另一个参数:

public function domain_host()
{
    return $this->hasOne('App\DomainHost', 'id', 'domain_host_id');
}

public function server_host()
{
    return $this->hasOne('App\ServerHost', 'id', 'server_host_id');
}

public function system()
{
    return $this->hasOne('App\System', 'id', 'system_id');
}

它正在另一个 table 中查找当前行的 ID。