2015-11-03 74 views
0

重寫我有了一個範圍的方法來過濾一些行雄辯的模型:機型ID通過相關模型

class TODocs extends \Eloquent { 
    public function scopeUnexported($query) 
    { 
     $query 
      ->join('to_requests', function ($join) { 
       $join->on('to_requests.id', '=', 'to_docs.request_id'); 
       $join->whereNull('to_requests.deleted_at'); 
      }) 
      ->where('to_docs.export_allowed', true) 
      ->whereNotNull('to_docs.filename') 
      ->whereNull('to_docs.exported_at'); 

     return $query; 
    } 
} 

但是,當我拿到導致該範圍內的所有對象都具有的ID號從to_requests表。

舉例來說,如果我試圖讓從具有id = 1to_docs表中的一行和該行有一個外鍵to_docs.request_id = 2然後爲模型我得到的ID也。然而,當我刪除範圍join節法比一切工作就像一個魅力,id是1

我可能擺脫join但我需要這個條件讓行外國紀錄to_requests.deleted_at IS NULL

有沒有辦法解決這個問題的方法?

回答

0

我終於解決了這個問題。我知道問題在加入;但是,我無法刪除它,因爲我需要在連接的表中引用字段值。所以我加\Illuminate\Database\Query\Builder::select只從主表中提取字段

public function scopeUnexported($query) 
{ 
    $query 
     ->select('to_docs.*') 
     ->join('to_requests', function ($join) { 
      $join->on('to_requests.id', '=', 'to_docs.request_id'); 
      $join->whereNull('to_requests.deleted_at'); 
     }) 
     ->where('to_docs.export_allowed', true) 
     ->whereNotNull('to_docs.filename') 
     ->whereNull('to_docs.exported_at'); 

    return $query; 
} 
0

這不是嚴格的Laravel問題(或解決方案),因爲這是mysql查詢覆蓋空連接字段的默認行爲。請參閱提供查詢解決方案的此回答Join - fields in table 2 override those in table 1。一個更好,更Laravelish的方式,將使用急切的加載(尤其是因爲你似乎沒有使用連接的數據進行排序)。見http://laravel.com/docs/5.1/eloquent-relationships#eager-loading

+0

確實,我不使用to_requests表中的數據進行排序;然而,我仍然需要這個連接來限制select來獲取與'to_requests.deteted_at IS NULL'相關的行。 – vansanblch