无法在 Laravel 4 中运行原始查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16601409/
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
Cannot run raw Query in Laravel 4
提问by Tanvir Gaus
I need to get total count to show in my page.
我需要让总数显示在我的页面中。
I can run this & loop through & get the total number
我可以运行这个 & 循环 & 得到总数
DB::table('table1')
->select((DB::raw('MAX(score)')))
->where('status', 1)
->groupBy('user_id')
->get();
But this query would give me the count in just a single query & I don't need run any extra loop to get the total.
但是这个查询只会给我一个查询的计数,我不需要运行任何额外的循环来获得总数。
SELECT COUNT( * ) FROM (
SELECT MAX( score ) FROM table1
WHERE status =1
GROUP BY user_id
) AS totalCounter
How am I suppose to run this RAW query in Laravel 4?
我该如何在 Laravel 4 中运行这个 RAW 查询?
回答by Safeer
Try
尝试
DB::statement( 'Your Query' );
or
或者
DB::select( 'Your Query' );
回答by Shayne
As mentioned by other contributors;-
正如其他贡献者所提到的;-
DB::select('SQL QUERY GOES HERE WITH PARAMETERS ?, ?', array('parameter 1', 'parameter 2'));
The code above should permit raw sql.
上面的代码应该允许原始 sql。
However,
然而,
DB::table('table1')
->select((DB::raw('MAX(score)')))
->where('status','=', 1)
->groupBy('user_id')
->count();
Should achieve the same effect for the task you seek it for, and is more in tune with laravels philosophy.
应该为您寻求的任务达到相同的效果,并且更符合 laravel 的哲学。
回答by tfont
DB::select(DB::raw("SQL QUERY CODE HERE"))
Both raw and select are require!
raw 和 select 都是必需的!
Please see for more info: Laravel 4: how to run a raw SQL?
请参阅了解更多信息: Laravel 4:如何运行原始 SQL?
回答by Manish
Try this
尝试这个
DB::select( DB::raw("SELECT * FROM table_Name WHERE col = :somevariable"), array(
'somevariable' => $someVariable,
));