我一直在尝试一个查询,我想在相关的表上做一些验证。我想用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');另外,table1与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中唯一存在的项。指的是使用table2中的项目进行的所有交易。假设table2中的项的id分别为123、456和789,那么我希望显示与此id相关的所有记录
我怎样才能得到这样的结果呢?
发布于 2015-10-08 20:00:25
您可以使用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关系名称。
https://stackoverflow.com/questions/33007904
复制相似问题