2017-09-20 60 views
1

我有2个关系Company和DamageReport的模型。Laravel具有关系的雄辩查询模型

DamageReport始终通过关键company_id链接到公司。

因此DamageReport中的company_id等于公司中的id。

很简单吧?现在我的目标是在知道DamageReport的ID时查询公司。

例如

我有DamageReport表的一行:

id company_id 

6 1 

而且公司与ID的记录是:

id name 

1 Company 1 

所以在我的控制器我有DamageReport id(6)并需要查询id为1的公司。

我已经建立了一种关系这在我的模型

公司型号:

/** 
* The Damage Reprots that belong to the Company. 
*/ 
public function damageReports() 
{ 
    return $this->belongsToMany('App\DamageReport'); 
} 

DamageReport型号:

/** 
* The company of a damagereport 
* 
*/ 
public function company() 
{ 
    return $this->belongsTo('App\Company'); 
} 

现在在我的控制器,我想是这样的,但我真的不知道

$company = new Company; 

$company = $company->company($damageReportId); 

dd($company); 

回答

2

你的关系是错误的。

应该

Company model: 

/** 
* The Damage Reprots that belong to the Company. 
*/ 
public function damageReports() 
{ 
    return $this->hasMany('App\DamageReport'); 
} 


DamageReport model: 

/** 
* The company of a damagereport 
* 
*/ 
public function company() 
{ 
    return $this->belongsTo('App\Company'); 
} 


// In your controller 
public function index() 
{ 
    $damageReportId = 1; 
    $company = Company::whereHas('damageReports', function ($q) use($damageReportId) { 
     $q->where('id', $damageReportId); 
    })->first(); 

    dd($company); 
} 

// Or 
public function index() 
{ 
    $damageReportId = 1; 
    $company = DamageReport::find($damageReportId)->company; 
    dd($company); 
} 
1

您应该使用:

$company = DamageReport::find($damageReportId)->company; 

说明:

DamageReport是你知道的东西,所以find($id)方法带回你有$id为单一的模式。

由于DamageReportCompany的关系设置正确,因此->company关系将带回关联的公司模型。

+0

是的,就是这样的感谢! – Chris

0

只要使用belongsTohasMany方法,如果关系是一对多。

https://laravel.com/docs/5.5/eloquent-relationships#one-to-many

所以,你DamageReport模型是正确的,在你的Company模型,

/** 
* The Damage Reprots that belong to the Company. 
*/ 
public function damageReports() 
{ 
    return $this->hasMany('App\DamageReport'); 
} 

然后在你的控制器,@ Skrrp的答案是正确的,

$company = DamageReport::find($damageReportId)->company;