Initial SQL to list clients (PF and PJ). How to migrate a pure SQL Query to Laravel Eloquent?

Asked

Viewed 83 times

0

I set up an initial SQL to pull the data. It’s working in pure SQL. I need to migrate this code to Laravel’s eloquent pattern. Can anyone help me? Thank you!

Follow the example SQL:

inserir a descrição da imagem aqui

Code:

SELECT c.cod_cliente, p.cpf, p.nome, ct_mpf.cod_contrato_pessoa_fisica_plano, ct_mpf.numero_contrato_membro AS numero_contrato_membro_pf, pjc.cod_contrato_pessoa_juridica_plano, pjc.numero_contrato_membro AS numero_contrato_membro_pj, pj.razao_social,
(
CASE
    WHEN c.usufrui_de_um_contrato = 1 
    THEN 
        CASE
            WHEN ct_mpf.vinculo = 1 THEN 'membro' 
            WHEN ct_mpf.vinculo = 2 THEN 'rf_membro' 
            WHEN ct_mpf.vinculo = 3 THEN 'rf'
            ELSE null
        END 
    WHEN c.usufrui_de_um_contrato = 2 
    THEN 
        CASE
            WHEN pjc.vinculo = 1 THEN 'membro' 
            WHEN pjc.vinculo = 2 THEN 'submembro'
            ELSE null
        END 
END
) AS vinculo
FROM pessoa AS p
LEFT JOIN clientes AS c ON c.cod_pessoa = p.cod_pessoa
LEFT JOIN pessoa_fisica AS pf ON pf.cod_cliente = c.cod_cliente
LEFT JOIN 
(
    SELECT ctpf.cod_pessoa_fisica AS pf_do_contrato, m.cod_pessoa_fisica AS pf_do_membro, ctpf.cod_contrato_pessoa_fisica_plano, m.numero_contrato_membro, m.vinculo
    FROM contratos_pessoa_fisica_planos AS ctpf
    INNER JOIN membros AS m
    ON ctpf.cod_contrato_pessoa_fisica_plano = m.cod_contrato_pessoa_fisica_plano
    WHERE ctpf.status = 1 AND m.status = 1
    ORDER BY ctpf.created_at DESC
) AS ct_mpf ON ct_mpf.pf_do_contrato = pf.cod_pessoa_fisica AND ct_mpf.pf_do_membro = pf.cod_pessoa_fisica
LEFT JOIN pessoa_juridica_clientes AS pjc ON pjc.cod_cliente = c.cod_cliente
LEFT JOIN pessoa_juridica AS pj ON pj.cod_pessoa_juridica = pjc.cod_pessoa_juridica
WHERE p.cpf = 12345 OR p.nome LIKE '%JOSUE%
  • What have you ever tried to do?

  • Have you created Models for person, customers, personal, etc? The first step will be to create these models, with their respective relationships (See the official documentation: https://laravel.com/docs/5.6/eloquent) Then you can do the treatment you need in a Controller. There are more direct ways to do these searches using Eloquent, but if you want, you also have the possibility to execute an sql code directly through the "Raw Methods" (https://laravel.com/docs/5.6/queries#raw-Expressions) Take a look at this link too: https://laravel.com/docs/5.6/queries Hugs!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.