简体   繁体   中英

Relationships returning wrong/null data (Laravel 5.2)

Got a domain table which has a One To Many relationship with domain_hosts_table , server_hosts_table and systems_table . So far so good.

Calling the table data:

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

Domain model :

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');
}

DomainHost , ServerHost , System model :

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

Domains table :

在此处输入图片说明

So far so good.

Let's take a look at what this particular table returns while being foreached .

在此处输入图片说明

The first 2 rows should be the same (basing on their IDs), and all rows after the first 2 are just empty.

( dd of the fetched data, notice the relations being empty at 4th object, 1st object actually has data).

在此处输入图片说明

Had to define another parameter when defining my relationships:

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');
}

It was looking for the ID of the current row in the other table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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