2017-09-20 11 views
1

私は、CompanyとDamageReportという2つのモデルを持っています。Laravelリレーションシップを持つ奇妙なクエリモデル

DamageReportは常にcompany_idというキーで会社にリンクされます。

DamageReportのcompany_idはCompanyの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を持つ単一のモデルを取り戻すだろう。

DamageReportは、Companyとの関係が正しく設定されているため、->companyという関係は、関連付けられた会社のモデルを返します。

+0

はい、それはそれだおかげでなければなりません! – Chris

0

関係が1対多である場合は、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; 
関連する問題