mysql - 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 ()'
,但它也没有工作。
你可以帮帮我吗?
解决方案
在这里,我假设您正在尝试比较 2 列,对吗?
->where('mygame_id', 'mygames.id');
在这种情况下,请使用该whereColumn/orWhereColumn
方法。
->whereColumn('mygame_id', 'mygames.id')
推荐阅读
- file - 在 Golang 中写入响应后,HTTP 请求被中止
- java - Spring-data-cassandra:创建名为“sessionFactory”的bean时出错,并且无法解析对bean“cassandraTemplate”的引用
- c++ - 调整和复制哈希表数组中的元素
- c# - 使用 Polly 重试处理较长时间间隔的 HTTP 请求错误是否安全
- c - 如何检查矩阵中的哪些行和列等于哪些行和列
- powershell - 为什么“abc [2] d c”-match“bc [2]”是假的?
- ruby-on-rails - 如何避免破坏删除较早的相关对象
- azure - 从 Azure 数据工厂 (ADF) 查找 Azure AD
- sql - 是否可以从下到上填充 GridView,而不是从上到下?
- bash - 无法在 VS 代码中运行飞镖程序