2017-10-21 456 views
0

我即將對查詢感到瘋狂,有人可以幫助我翻譯查詢以在laravel中工作,或以「laravel方式」編寫。加入laravel的子查詢

查詢代碼如下,它使用MySQL。

我被卡住的部分是在第一個加入子查詢到另一個加入它。

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

爲什麼不laravel插入原始查詢? –

+0

如果您不打算使用其他數據庫類型,則可以使用'DB :: raw()'並使用原始SQL查詢。節省您的工作量。 – Jeffrey

+1

「Laravel的方式」將是定義所有的模型和關係,並使用雄辯。 – Camilo

回答

1

嘗試發送子查詢作爲原料表達如在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

+0

我試過這個選項,但由於某種原因,它過濾了一些結果,因爲我的ETA,我無法弄清楚爲什麼。所以我用了一個原始查詢。謝謝 –

0

多虧了回答,幾個測試後,我會選擇使用DB ::表原始查詢所有用戶和它的工作非常出色

謝謝大家。

0

您可以嘗試我的Eloquent extension enabling subqueries inside eloquent正是爲這種情況而設計的。

在您的樣品將是

User::selectRaw(....) 
->leftJoinSubquery(UserLogs::where(...)->leftJoin(...), 
    'temp', 
    function ($join) { 
     $join->on('users.id', '=', 'temp.user_id'); 
    } 
)