How to implement my sql statement in Laravel?

后端 未结 1 644
青春惊慌失措
青春惊慌失措 2021-01-15 09:46

I have the following MySQL query which works fine. It returns Random results from my table.

SET @prev=0,@rownum=0;
SELECT utilizador_id, nome 
FROM (
  SELEC         


        
1条回答
  •  有刺的猬
    2021-01-15 10:16

    You can solve this by using DB::statement, DB:raw and DB::select.

    The code is tested on my Laravel 5.0 test environment and it works perfectly.

    Your mysql statement is also tested it works perfectly on MySQL console.

    Here is the code:

    DB::statement(DB::raw('SET @prev=0,@rownum=0'));
    
    $results =
        DB::select(
            DB::raw("
              SELECT utilizador_id, nome
              FROM (
                SELECT *,
                     IF( @prev <> utilizador_id,
                         @rownum := 1,
                         @rownum := @rownum+1
                     ) AS rank,
                     @prev := utilizador_id,
                     @rownum
                FROM (
                  SELECT * FROM `anuncios`
                  ORDER BY utilizador_id, rand()
                ) AS random_ads
              ) AS ads_ranked
              WHERE rank <= 2;
            ")
        );
    

    View results

    echo "utilizador_id | nome 
    "; foreach ($results as $result) { echo $result->utilizador_id . "__________| " . $result->nome . "
    "; }

    Remember to added use DB; after the name space:

    I have made View results code only to demonstrate all results output, but it is up to you how to manipulate the data in your code.

    Test results

    Random results of your mysql statement in MySQL console Random results from MySQL

    Random results of your mysql statement in Laravel Random results in Laravel

    Note:

    1- I have solved this question my self for you but I faced a little issue and I got input from Kryptonit3 in Laracast forum.

    2- You might find other solutions to this question or it can be solved in different ways, but I have chosen to solve this way.

    The full question and answer in Note 1, can be found here.

    0 讨论(0)
提交回复
热议问题