如何加载多级关系?

时间:2018-04-20 12:02:39

标签: php laravel relationship

我正在尝试搜索3个相关的表,如下所示:contract belongsTo - >公司hasMany - > company_addresses.I想在合同视图中显示company_addresses数据。

contracts
    id – integer
    company_id - integer
    title – string 

companies
    id - integer
    name – string

company_addresses
    id - integer
    company_id - integer
    address – string
    complement – string
    contact– string

模型合同

public function company()
{
    return $this->belongsTo(Company::class, 'company_id', 'id');
}

模特公司

public function contracts ()
{
    return $this->hasMany(Contract::class);
} 
public function addresses()
{
    return $this->hasMany(CompanyAddress::class);
}

模型company_addresses

public function company()
{
    return $this->belongsTo(Company::class);
}

代码合同控制器

 public function index()
 {
     $contract= Contract::with('companies.company_addresses')->get();
     return view(‘contract.view')->with(compact('contract'));
 }

那么我做错了什么以及如何解决?任何帮助都是非常有效的。

1 个答案:

答案 0 :(得分:4)

你错了孩子。改变这个:

$contract= Contract::with('companies.company_addresses')->get();

到这个

$contract= Contract::with('company.addresses')->get();