How can I query raw via Eloquent?

前端 未结 8 1216
眼角桃花
眼角桃花 2020-12-02 20:42

I am trying to do a query in my Laravel app and I want to use a normal structure for my query. This class either does use Eloquent so I need to find something to do a query

8条回答
  •  北海茫月
    2020-12-02 21:03

    You may try this:

    // query can't be select * from table where
    Model::select(DB::raw('query'))->get();
    

    An Example:

    Model::select(DB::raw('query'))
         ->whereNull('deleted_at')
         ->orderBy('id')
         ->get();
    

    Also, you may use something like this (Using Query Builder):

    $users = DB::table('users')
                     ->select(DB::raw('count(*) as user_count, status'))
                     ->where('status', '<>', 1)
                     ->groupBy('status')
                     ->get();
    

    Also, you may try something like this (Using Query Builder):

    $users = DB::select('select * from users where id = ?', array(1));
    $users = DB::select( DB::raw("select * from users where username = :username"), array('username' => Input::get("username")));
    

    Check more about Raw-Expressions on Laravel website.

提交回复
热议问题