【问题标题】:Wherein query to related tables其中查询相关表
【发布时间】:2016-01-05 14:38:38
【问题描述】:

我一直在尝试查询我想对相关表进行一些验证的位置。我想用 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 中唯一存在的项目。表示使用表 2 中的项目进行的所有交易。 假设 table2 中的项目的 id 为 123、456 和 789,那么我想显示与此 id 相关的所有记录

我怎样才能做出这样的结果

【问题讨论】:

标签: laravel laravel-4 laravel-5 eloquent laravel-5.1


【解决方案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 关系名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多