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

How to write custom query in model 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();
    }

但是不行。如何使用简单:DB::query("native SQL query")? 我试过了:

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

可能您正在搜索这个, 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(DB::raw(...))里面写select。尝试:

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

但是既然有强大的Eloquent模型,为什么还要自己写查询。

您可以使用

public function scopeLastSync($query)
    {

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