How to execute raw queries with Laravel 5.1?

后端 未结 3 372
执念已碎
执念已碎 2020-12-01 00:27

So I have this tiny query to run on my DB and it works fine in MySQL Workbench. Basically, a SELECT with LEFT JOIN and UNION with LEFT JOIN again.

SELECT
            


        
相关标签:
3条回答
  • 2020-12-01 01:10
        DB::statement("your query")
    

    I used it for add index to column in migration

    0 讨论(0)
  • 2020-12-01 01:16

    you can run raw query like this way too.

    DB::table('setting_colleges')->first();
    
    0 讨论(0)
  • 2020-12-01 01:18

    I found the solution in this topic and I code this:

    $cards = DB::select("SELECT
            cards.id_card,
            cards.hash_card,
            cards.`table`,
            users.name,
            0 as total,
            cards.card_status,
            cards.created_at as last_update
        FROM cards
        LEFT JOIN users
        ON users.id_user = cards.id_user
        WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
        UNION
        SELECT
            cards.id_card,
            orders.hash_card,
            cards.`table`,
            users.name,
            sum(orders.quantity*orders.product_price) as total, 
            cards.card_status, 
            max(orders.created_at) last_update 
        FROM menu.orders
        LEFT JOIN cards
        ON cards.hash_card = orders.hash_card
        LEFT JOIN users
        ON users.id_user = cards.id_user
        GROUP BY hash_card
        ORDER BY id_card ASC");
    
    0 讨论(0)
提交回复
热议问题