2015-10-08 68 views
0

我一直在嘗試查詢,我想在相關表格上做一些驗證。我想使用Laravel 5其中查詢到相關表格

select 
    * 
from 
    table1 
    INNER JOIN table3 on(table1.id = table3.table1_id) 
    INNER JOIN table2 on(table1.id = table2.table1_id) 
where 
    table2.column2 in ('arr1', 'arr2'); 

而且表1是與5至做這樣的事情 - 7桌,我想急於負載了這一切。這是我到目前爲止

$reports = Table1::with(
     [ 
      'table3', 
      'table4', 
      'table5.table6', 
      'table7', 
      'table8', 
     ]) 
     ->where('created_at', '>=', date('Y-m-d', strtotime($request->get('from')))) 
     ->where('created_at', '<', date('Y-m-d', strtotime($request->get('to')))) 
     ->with('table2',function($query) use($table1_column){ 
       return $query->whereIn('table1_column',$table1_column); 
     }); 

但是這顯示了一切。即使是table2中不存在的項目。我想實現的是創建一個結果,其中所有項目是table2中唯一存在的項目。表示使用表2中的項目進行的所有事務。 假設表2中的項目有123,456和789的IDS那麼我想,以顯示與所有記錄這個ID的

我怎樣才能使這種結果

+0

查詢關係:http://laravel.com/docs/5.1/eloquent-relationships#querying-relations –

回答

1

可以使用whereHas方法。

$reports = Table1::with(
    [ 
     'table3', 
     'table4', 
     'table5.table6', 
     'table7', 
     'table8', 
    ]) 
    ->whereHas('table2', function($query) use($table1_column){ 
      return $query->whereIn('table1_column',$table1_column); 
    }) 
    ->where('created_at', '>=', date('Y-m-d', strtotime($request->get('from')))) 
    ->where('created_at', '<', date('Y-m-d', strtotime($request->get('to')))); 

請注意,這不包括結果集中的表2數據。如果您需要在with方法調用中包含table2關係名稱。