laravel Eloquent 更新和限制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16918972/
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
Eloquent update and limit
提问by Sercan V?RLAN
I could not figure out how can i use both update and limit methods in laravel eloquent orm.
我不知道如何在 laravel eloquent orm 中同时使用 update 和 limit 方法。
$affectedRows = Promo::where('used','=',0)
->update(array('user_id' => Auth::user()->id))
->limit(1); // Call to a member function limit() on a non-object
//->take(1); // Call to a member function take() on a non-object
I tried both limit and take methods.
我尝试了 limit 和 take 方法。
I want to do only one result will be update.
我只想做一个结果就是更新。
But i think, i can not use limit or take methods on update.
但我认为,我不能在更新时使用限制或采取方法。
Is there any way to update only one row via eloquent?
有没有办法通过 eloquent 只更新一行?
Add :
添加 :
Eloquent ORM
雄辩的 ORM
$affectedRows = Promo::where('user_id','=',DB::raw('null'))->take(1)
->update(
array(
'user_id' => Auth::user()->id,
'created_ip' =>Request::getClientIp(),
'created_at' => new DateTime,
'updated_at' => new DateTime
)
);
Query Builder
查询生成器
$affectedRows = DB::table('promos')->whereNull('user_id')
->take(1)
->update(array(
'user_id' => Auth::user()->id,
'created_ip' =>Request::getClientIp(),
'created_at' => new DateTime,
'updated_at' => new DateTime
));
These two codes did not add limit param to the query
这两个代码没有在查询中添加限制参数
Output:
输出:
update `promos` set `user_id` = '1', `created_ip` = '127.0.0.1', `created_at` = '2013-06-04 14:09:53', `updated_at` = '2013-06-04 14:09:53' where `user_id` = null
回答by Sercan V?RLAN
I used raw query. There is no method limit/take for update and delete queries on both eloquent and query builder. Use
我使用了原始查询。eloquent 和查询构建器上的更新和删除查询没有方法限制/采用。用
DB::update(DB::raw("UPDATE query"));
like this.
像这样。
回答by Pablo
Talking about laravel 5 (not sure about L4), depends on db engine. MySQL supports limit for update so it works, here is the laravel code that do that:
谈论 Laravel 5(不确定 L4),取决于数据库引擎。MySQL 支持更新限制,因此它可以工作,这是执行此操作的 Laravel 代码:
so, first ->limit(1) and then ->update([fields]);
所以,首先 ->limit(1) 然后 ->update([fields]);
DB::table('table')
->where('field', 'value')
->limit(1)
->update(['field', 'new value']);
回答by Alexandre Butynski
I have not tried it but the Laravel 4 logic makes me think this syntax would work :
我还没有尝试过,但 Laravel 4 逻辑让我认为这种语法可行:
$affectedRows = Promo::where('used','=',0)
->limit(1)
->update(array('user_id' => Auth::user()->id));