我要遍历此查询的多次迭代,我假设我在查询中某处遗漏了一些东西,导致我收到如下错误:
关闭类的对象无法转换为字符串
我的查询:
$test = UnitStandard::select(DB::raw("
count(t1.code),
t1.code,
t1.id,
t1.provider_id,
t1.name,
t1.nqf_level,
t1.credits,
t1.type,
MAX(t1.shared_id),
setas.name as setaName,
providers.name as providerName
"))
->from(function ($query){
$query->select(DB::raw("*"))
->from("unit_standards")
->where("provider_id", "=", 1)
->whereNull("shared_id")
->orWhere("shared_id", "=", 2)
->orderBy("unit_standards.code", "asc");
})
->join('setas', 't1.seta_id', '=', 'setas.id')
->join('providers', 't1.provider_id', '=', 'providers.id')
->where('shared_id', '=', 2)
->orWhere('t1.provider_id', '=', 1)
->groupBy('code')
->havingRaw('COUNT(code) >= 1')
->orderBy('code', 'asc')
->paginate(50);
查看下面的完整错误代码段
原始的MySQL:
SELECT
count(t1.code),
t1.code,
t1.id,
t1.provider_id,
t1.name,
t1.nqf_level,
t1.credits,
t1.type,
MAX(t1.shared_id),
setas.name as setaName,
providers.name as providerName
FROM(
SELECT * FROM unit_standards WHERE (provider_id = 1 AND shared_id IS NULL) OR shared_id = 2 ORDER BY `unit_standards`.`code` ASC
) AS t1
JOIN setas on t1.seta_id = setas.id
JOIN providers on t1.provider_id = providers.id
WHERE t1.shared_id = 2 OR t1.provider_id = 1
GROUP BY code
HAVING COUNT(code) >= 1
ORDER BY code ASC
LIMIT 50
答案 0 :(得分:0)
由于@NigelRen的建议,我得以解决自己遇到的问题。感谢您的协助。但是,如果有人知道如何通过单个查询获得相同的结果,那将不胜感激。
解决方案在这里找到:How to write select query with subquery using laravel Eloquent Querybuilder?
$subQuery = DB::table('unit_standards')->selectRaw('nqf_level,name, id, code, provider_id, shared_id, COUNT(code) as totalCodeCount, credits, type, seta_id')
->where('provider_id', '=', '1')
->whereNull('shared_id')
->orWhere('shared_id', '=', '2')
->groupBy('id','code','provider_id', 'shared_id', 'name', 'nqf_level', 'credits', 'type', 'seta_id')
->orderBy("code", "asc");
$sharedUnitstandards = \DB::table(\DB::raw('('.$subQuery->toSql().') as t1'))
->selectRaw("t1.code, t1.id, t1.provider_id, t1.name, t1.nqf_level, t1.credits, t1.type, MAX(t1.shared_id) ,setas.name as setaName, providers.name as providerName")
->mergeBindings($subQuery)
->join('setas', 't1.seta_id', '=', 'setas.id')
->join('providers', 't1.provider_id', '=', 'providers.id')
->where('t1.shared_id', '=', 2)
->orWhere('t1.provider_id', '=', 1)
->groupBy('t1.code','t1.code','t1.id','t1.provider_id','t1.name', 't1.nqf_level', 't1.credits','t1.type','t1.shared_id', 't1.seta_id', 'setas.name', 'providers.name')
->havingRaw('COUNT(t1.code) >= 1')
->orderBy('t1.code', 'asc')
->paginate(50);