【问题标题】:Where clause to filter rows from three related tables using the Eloquent ORM in Laravel使用 Laravel 中的 Eloquent ORM 从三个相关表中过滤行的 Where 子句
【发布时间】:2018-02-09 10:22:31
【问题描述】:

我们有三个相关的模型:Event、User 和 EventType。

模型事件有一个用户,也有一个事件类型。

现在,我们正在实现一个表格 (UI),用户可以从 Web 浏览器中过滤该表格。用户可以按事件类型、用户名(生成事件的)以及其他字段(如 IP 地址)进行过滤。

IP 地址存储在Events 表中,但Events 表有两个外键,user_id 和event_type_id。那么我如何才能使用由某个用户生成并具有某个 event_type 的 eloquent 事件进行过滤呢?

到目前为止,我们使用一个查询来检索具有特定名称的所有事件以及满足用户名搜索条件的所有用户。

然后使用 whereIn 子句构建第三个查询,按 user_id 和 event_type_id 进行过滤。

但是,这是三个查询。

【问题讨论】:

    标签: laravel eloquent laravel-5.3


    【解决方案1】:

    尝试以下方法:

    Event::whereHas('user', static function($query){
    
       $query->where('users.name', 'Some Value');
    
    })->whereHas('eventType', static function($query) {
    
       $query->where('event_types.field', '!=', 'Some other value');
    
    })->where('ip', 'localhost)->get();
    

    假设Event 模型中与User 的关系称为user(),与EventType 的关系称为eventType()。同样在嵌套的whereHas 查询中,我假设User 表称为usersEventType 表称为event_types。使用您的实际值相应地更改它们。

    但是whereHas方法实际上是在执行一个查询,所以查询的数量不会减少,仍然是3。为了减少查询的数量join是要走的路:

    Event::select('events.*)->join('users as u', 'events.user_id', 'u.id')
    ->join('event_types as et', 'events.event_type_id', 'et.id')
    ->where('u.username', 'like', "%$search%")
    ->where('et.slug', 'user.created')
    ->where('ip', 'localhost');
    

    【讨论】:

      猜你喜欢
      • 2015-04-21
      • 2015-04-04
      • 2014-08-19
      • 2019-11-27
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      • 2020-05-29
      • 2016-06-13
      相关资源
      最近更新 更多