2016-08-22 71 views
0

我一直堅持這幾天,現在想知道是否有人可以提供幫助。Laravel 5.2子查詢 - 通過多態樞軸表最後一行篩選行

數據庫表: '頁', '狀態', 'status_assignments'

頁型號:

protected $appends = ['status']; 

public function statuses() 
{ 
    return $this->morphToMany('App\Models\Status', 'statusable', 'status_assignments')->withPivot('id', 'assigned_by_user_id', 'locked')->withTimestamps(); 
} 

public function getStatusAttribute() 
{ 
    return $this->statuses()->orderBy('pivot_id', 'DESC')->first(); 
} 

public function scopeWithStatus($query, $statuses) 
{ 
    $query->with('statuses'); 

    if(is_array($statuses) && count($statuses) > 0) 
    { 
     $query->whereHas('statuses', function($q) use($statuses) 
     { 
      $cs = $q->orderBy('pivot_id', 'DESC')->first(); 
      foreach($statuses as $status) $q->where('id', $status)->where('pivot_id', $cs->pivot->id); 
     }); 
    } 

    return $query; 
} 

狀態型號:

public function pages() 
{ 
    return $this->morphedByMany('App\Models\Page', 'categorizable', 'category_assignments')->withTimestamps(); 
} 

我想要做的檢索分配了最新狀態的id爲['array_of_status_ids'](範圍內狀態爲「$ status」)的頁面列表

$pages = Page::withStatus([1,2,3,4])->get(); 

關於此問題的任何建議都會非常感激!在此先感謝克里斯。

回答

0

首先,pages()關係看起來像它使用了錯誤的數據透視表細節。

'categorizable', 'category_assignments'

如果那些是'statusable', 'status_assignments'

有時我發現在混合中拋出一些原始SQL比編寫複雜的Query Builder語句更簡單。

使用子查詢來檢查每個頁面的最新狀態條目包含在 $statuses

public function scopeWithStatuses($query, $statuses = []) 
{ 
    $subQuery = '(select status_id from status_assignments' 
     . ' where status_assignments.statusable_id = pages.id' 
     . ' and status_assignments.statusable_type = "App\\\Test\\\Page"' 
     . ' order by status_assignments.id desc limit 1)'; 

    $query->whereIn(\DB::raw($subQuery), (array) $statuses); 
} 
+0

你是一個傳說我的朋友 –