首页 > 解决方案 > Laravel - 如何使用子查询创建带有 where 子句的查询?

问题描述

我正在尝试使用 Laravel 生成此查询:

select mygames.id, mygames.name, mygames.slug, mygames.cover from mygames 
left join mygame_mygenre on mygames.id = mygame_mygenre.mygame_id 
left join mygame_myplatform on mygames.id = mygame_myplatform.mygame_id 
where mygame_mygenre.mygenre_id in (8, 9, 31, 32, 33) 
and mygame_myplatform.myplatform_id in (3, 6, 14, 34, 37, 39, 46, 48, 72, 130) 
and mygames.id <> 1990
and mygames.summary is not null 
and (select count(mygame_id) from mygame_myplatform where mygame_id = mygames.id) > 1 
group by mygames.id, mygames.name, mygames.slug, cover 
order by RAND() 
limit 6

我目前的代码是:

$games = DB::table('mygames')
            ->leftjoin('mygame_mygenre', 'mygames.id', '=', 'mygame_mygenre.mygame_id')
            ->leftjoin('mygame_myplatform', 'mygames.id', '=', 'mygame_myplatform.mygame_id')
            ->select('mygames.id', 'mygames.name', 'mygames.slug', 'cover')
            ->when($genres_id, function ($query, $genres_id) {
                return $query->whereIn('mygame_mygenre.mygenre_id', $genres_id);
            })
            ->when($platforms_id, function ($query, $platforms_id) {
                return $query->whereIn('mygame_myplatform.myplatform_id', $platforms_id);
            })
            ->where('mygames.id', '<>', $this->id)
            ->whereNotNull('mygames.summary')
            ->where(function ($query) {
                $query->selectRaw('count(mygame_id)')
                ->from('mygame_myplatform')
                ->where('mygame_id', 'mygames.id');
            }, '>', 1)
            ->groupBy('mygames.id', 'mygames.name', 'mygames.slug', 'cover')
            ->inRandomOrder()
            ->take(6)
            ->get();

此代码不起作用,因为在闭包函数中我无法将 mygames 表的名称与 id 字段一起传递。Laravel 被解释为文本参数而不是 table.field

->where(function ($query) {
                    $query->selectRaw('count(mygame_id)')
                    ->from('mygame_myplatform')
                    ->where('mygame_id', 'mygames.id'); <<<<<<<<<<<<<
                }, '>', 1)

我尝试使用'use ()',但它也没有工作。

你可以帮帮我吗?

标签: mysqllaraveleloquent

解决方案


在这里,我假设您正在尝试比较 2 列,对吗?

->where('mygame_id', 'mygames.id');

在这种情况下,请使用该whereColumn/orWhereColumn方法。

->whereColumn('mygame_id', 'mygames.id')

推荐阅读