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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44470703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:06:46  来源:igfitidea点击:

How to write custom query in model Laravel?

laravellaravel-5laravel-5.3

提问by sdfsf

I tried to write custom query in model as local scope:

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

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();
    }

But it does not work. How to use easy: DB::query("native SQL query")? I tried:

但它不起作用。如何使用简单: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)");

采纳答案by Sagar Chamling

May be you are searching for this, Write Custom query in laravel 5

可能你正在寻找这个, 在 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....' );

You don't have to write selectinside select(DB::raw(...)). Try:

你不必写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();
    }

But why to do you want to write query of your own if there is powerful Eloquent Model.

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

回答by Usman Sharif

YOU CAN USE

您可以使用

public function scopeLastSync($query)
    {

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