我有2个具有Company和DamageReport关系的模型。
DamageReport始终通过关键的company_id与公司链接。
因此,DamageReport中的company_id等于Company中的id。
很简单,对吧?现在,我的目标是在知道损害报告的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);
你的关系是错的。
它应该是
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句