2015-11-03 101 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

相关问题