私には、環境、サイト、インシデントの3つのモデルがあります。それぞれにそれぞれのテーブルがあります。
私のモデルの関係は次のように定義されています。
環境には多くのサイトがあります(environment_id
サイトテーブル内)
public function sites()
{
return $this->hasMany('App\Site');
}
サイトは、(環境に属しているenvironment_id
サイトのテーブルに)、多くのインシデントに属している(とincident_site関係テーブルincident_id
とsite_id
)
public function environment()
{
return $this->belongsTo('App\Environment');
}
public function incidents()
{
return $this->belongsToMany('App\Incident');
}
インシデントは多くのサイトに属しています(incident_id
およびとのincident_site関係テーブルsite_id
)
public function sites()
{
return $this->belongsToMany('App\Site');
}
問題:次のような環境モデルを使用して、すべてのサイトインシデントのコレクションを取得しようとしています。
$environment->incidents()->count();
これまでコントローラーで動作させることができた唯一の方法は次のとおりです。
$environment->load(['sites.incidents' => function ($q) use ( &$incidents ) {
$incidents = $q->orderBy('id','desc')->get();
}]);
ただし、アプリの他の領域で作業することは理想的ではありません。
質問:環境モデルのメソッドを使用して、上記の関係を機能させるにはどうすればよいですか?もっと簡単な方法はありますか?
hasManyThrough()
多対多の関係で使用するための規定はありません。ただし、どちらDB::raw()
かを使用してこれを実現することも、このフォーラムで提供されているようにBaseModelに次の関数を追加することもできます。
public function manyThroughMany($related, $through, $firstKey, $secondKey, $pivotKey)
{
$model = new $related;
$table = $model->getTable();
$throughModel = new $through;
$pivot = $throughModel->getTable();
return $model
->join($pivot, $pivot . '.' . $pivotKey, '=', $table . '.' . $secondKey)
->select($table . '.*')
->where($pivot . '.' . $firstKey, '=', $this->id);
}
更新:使用
まず、次のモデルを作成する必要があります incident_site
class incident_site extends Model{
public $table = 'incident_site';
//your other code
}
Enviorment
モデルに次のIncidents()
メソッドを追加します。
public function Incidents()
{
return $this->manyThroughMany('App\Incident', 'App\incident_site', 'site_id', 'id', 'incident_id');
}
必要に応じて機能を変更しました。
関数を次のように変更します。
public function manyThroughMany($related, $through ,$middle , $firstKey, $secondKey, $pivotKey)
{
$model = new $related;
$table = $model->getTable();
$throughModel = new $through;
$pivot = $throughModel->getTable();
$middleModel = new $middle;
$middleModelIds = $middleModel->where($this->getForeignKey(),$this->getKey())->get()->lists('id')->toArray();
//$middleModelIds = $this->with($middleModel)->where()->get()->lists('id')->toArray();
//$middleModelIds = $this->sites()->get()->lists('id')->toArray();
return $model
->join($pivot, $pivot . '.' . $pivotKey, '=', $table . '.' . $secondKey)
->select($table . '.*')
->whereIn($pivot . '.' . $firstKey,$middleModelIds);// '=', $this->id);
}
使用法:
中間テーブルの追加の引数を渡す必要があります。
public function Incidents()
{
return $this->manyThroughMany('App\Incident', 'App\incident_site','App\Site','site_id', 'id', 'incident_id');
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加