我即将对某个查询发疯,有人可以帮我翻译一个查询,以便在laravel中工作,或者以" laravel方式编写"。
查询代码如下,并且使用MySQL。
我遇到的部分是在第一个JOIN中,子查询到另一个JOIN它。
SELECT
usr.token,
usr.id,
usr.username,
usr.sn,
usr.givenname,
usr.telefone_numero,
usr.active,
usr.unidade_id,
usr.divisao_id,
usr.secao_id,
clients.nick,
posto_grad.sigla AS quadro_sigla,
log_logradouro_complemento,
log_logr.nome AS log_logradouro_nome,
log_logr.cep AS log_logradouro_cep,
log_bairro.nome AS log_bairro_nome,
log_localidade.nome AS log_localidade_nome,
log_uf.sigla AS log_uf_sigla
FROM
users usr
LEFT JOIN
(SELECT
usr_log1.*
FROM
users_log_logradouro AS usr_log1
LEFT JOIN users_log_logradouro AS usr_log2 ON usr_log1.user_id = usr_log2.user_id
AND usr_log1.created_at < usr_log2.created_at
WHERE
usr_log2.user_id IS NULL) AS temp ON (usr.id = temp.user_id)
LEFT JOIN
log_logradouro log_logr ON temp.log_logradouro_id = log_logr.id
INNER JOIN
clients ON clients.matricula = usr.givenname
INNER JOIN
quadro ON quadro.id = clients.quadro_id
INNER JOIN
posto_graduacao posto_grad ON posto_grad.id = clients.posto_graduacao_id
LEFT JOIN
log_bairro ON log_logr.log_bairro_id = log_bairro.id
LEFT JOIN
log_localidade ON log_bairro.log_localidade_id = log_localidade.id
LEFT JOIN
log_uf ON log_localidade.log_uf_sigla = log_uf.sigla
WHERE
usr.departmentnumber IN (1,2,3,4)
答案 0 :(得分:2)
尝试将子查询作为原始表达式发送为 leftJoin()方法中的第一个参数,例如:
$subquery = '(SELECT
usr_log1.*
FROM
users_log_logradouro AS usr_log1
LEFT JOIN
users_log_logradouro AS usr_log2
ON usr_log1.user_id = usr_log2.user_id
AND usr_log1.created_at < usr_log2.created_at
WHERE
usr_log2.user_id IS NULL)
AS temp';
DB::table('users as usr')
->select(...)
->leftJoin(DB::raw($subquery), 'usr.id', '=', 'temp.user_id')
->leftJoin(...)
->join(...)
->join(...)
->join(...)
->leftJoin(...)
->leftJoin(...)
->leftJoin(...)
->where(...)
->get()
这些问题中有类似的例子:
Laravel Fluent Query Builder Join with subquery
How to write this (left join, subquery ) in Laravel 5.1?
更多信息abaut加入: https://laravel.com/docs/5.5/queries#joins
答案 1 :(得分:0)
感谢所有回答的用户,经过几次测试后,我选择使用带有原始查询的DB :: table,并且效果非常好
谢谢大家。
答案 2 :(得分:0)
您可以尝试完全针对此案例设计的Eloquent extension enabling subqueries inside eloquent。
在你的样本中它将是
User::selectRaw(....)
->leftJoinSubquery(UserLogs::where(...)->leftJoin(...),
'temp',
function ($join) {
$join->on('users.id', '=', 'temp.user_id');
}
)