2017-06-10 112 views
-1

我試着寫在模型局部範圍自定義查詢:如何在模型Laravel中編寫自定義查詢?

public function scopeLastSync($query) 
    { 

     return DB::table('clients') 
      ->select(DB::raw(
       "select COUNT(*) as total, (SELECT created_at FROM clients ORDER BY created_at DESC LIMIT 1)" 
      ))->get(); 
    } 

但它不工作。如何使用easy:DB :: query(「原生SQL查詢」)? 我想:

return DB::raw("select COUNT(*) as total, (SELECT created_at AS date_modify FROM clients ORDER BY created_at DESC LIMIT 1)"); 

回答

0

可能是你正在尋找此, Write Custom query in laravel 5

For Select --> DB::select('your query here.....'); 
For Insert --> DB::insert('your query here.....'); 
For Update --> DB::update('your query here.....'); 
For Delete --> DB::delete('your query here.....'); 
For General --> DB::statement('your query here....'); 

你不必寫selectselect(DB::raw(...))。嘗試:

return DB::table('clients') 
      ->select(DB::raw(
       "COUNT(*) as total, (SELECT created_at FROM clients ORDER BY created_at DESC LIMIT 1)" 
      ))->get(); 
    } 

但是,如果你想寫自己的查詢,如果有強大的雄辯模型,爲什麼你要寫?

-1

可以使用

public function scopeLastSync($query) 
    { 

     return DB::table('clients') 
      ->select(DB::raw(
       "select COUNT(*) as total, created_at)" 
      ))->orderBy('created_at','desc')->first(); 
    }