簡體   English   中英

Laravel 5.2雄辯-通過多對多關系進行建模

[英]Laravel 5.2 Eloquent - Model through Many-To-Many Relationship

我有3個模型:環境,站點和事件。 每個都有各自的表。

我的模型關系定義如下:

環境中有許多站點(站點表中的environment_id

public function sites()
{ 
   return $this->hasMany('App\Site');
}

站點屬於環境(站點表中的environment_id ),並且屬於許多突發事件(具有incident_idsite_id incident_site關系表)

public function environment()
{
    return $this->belongsTo('App\Environment');
}

public function incidents()
{
    return $this->belongsToMany('App\Incident');
}

事件屬於許多站點(具有incident_idsite_id incident_site關系表)

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');
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM