【问题标题】:Laravel 8 - Left Outer Join with multiple conditionsLaravel 8 - 具有多个条件的左外连接
【发布时间】:2021-02-08 06:01:18
【问题描述】:

在我的 Laravel 应用程序的某个部分,我需要使用左外连接来获取数据。如果连接只需要一个条件,那么我可以轻松处理这个问题(通过在 Laravel 连接子句中添加 left outer 作为参数),但我需要在左外连接中使用两个条件。到目前为止,我编写了以下查询:

$events = DB::table('events AS ev')
                    ->join('event_registrations AS er', function ($join) {
                        $join->on('ev.id', '=', 'er.event_id')
                            ->where('er.status', '=', 'confirmed');
                    })
                    ->select('ev.id', 'ev.event_name', 'ev.event_link', 'ev.description', 'ev.total_tickets', 'ev.logo_path', DB::raw("IFNULL( count(er.id), 0 ) as total_confirmed"))
                    ->groupByRaw("ev.id, ev.event_name, ev.event_link, ev.description, ev.total_tickets, ev.logo_path, ev.total_tickets")
                    ->get();

这会创建一个内部连接查询。我尝试按以下方式添加 left outer:

$events = DB::table('events AS ev')
                    ->join('event_registrations AS er', function ($join) {
                        $join->on('ev.id', '=', 'er.event_id')
                            ->where('er.status', '=', 'confirmed');
                    }, 'left outer')
                    ->select('ev.id', 'ev.event_name', 'ev.event_link', 'ev.description', 'ev.total_tickets', 'ev.logo_path', DB::raw("IFNULL( count(er.id), 0 ) as total_confirmed"))
                    ->groupByRaw("ev.id, ev.event_name, ev.event_link, ev.description, ev.total_tickets, ev.logo_path, ev.total_tickets")
                    ->get();

但它仍然会产生内连接。
有谁知道如何在 Laravel 中使用多个条件创建左外连接查询?

【问题讨论】:

  • 你可以像使用join一样使用leftJoin

标签: laravel laravel-8


【解决方案1】:

如果您查看 Illuminate\Database\Query\Builder.php 中的源代码
join方法是这样定义的。

/**
 * Add a join clause to the query.
 *
 * @param  string  $table
 * @param  \Closure|string  $first
 * @param  string|null  $operator
 * @param  string|null  $second
 * @param  string  $type
 * @param  bool  $where
 * @return $this
 */
public function join($table, $first, $operator = null, $second = null, $type = 'inner', $where = false)

所以 type 实际上是第五个参数,那么你的 join 应该是

->join('event_registrations AS er', function ($join) {}, null, null, 'left outer')

【讨论】:

    猜你喜欢
    • 2012-01-08
    • 1970-01-01
    • 2010-11-10
    • 2018-08-16
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多