如何在模型Laravel中编写自定义查询?

时间:2017-06-10 07:22:48

标签: laravel laravel-5 laravel-5.3

我尝试在模型中将自定义查询编写为本地范围:

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)");

2 个答案:

答案 0 :(得分: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....' );

您不必在select内写select(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();
    }

但是,如果有强大的Eloquent模型,你为什么要编写自己的查询。

答案 1 :(得分:-1)

您可以使用

public function scopeLastSync($query)
    {

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