laravel 5.1:如何仅使用 where 子句更新一行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37254402/
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 13:48:49  来源:igfitidea点击:

laravel 5.1 : how can i update one row only with where clause?

laravellaravel-5

提问by Hamid Naghipour

I want update a row with only where clause. I don't have row id, only i have 2 where clause. Is it possible? (with eloquent)

我只想用 where 子句更新一行。我没有行 ID,只有 2 个 where 子句。是否可以?(口齿伶俐)

->where("x",1) ->where("y"=2)

回答by Joseph Silber

When using Active Record, you should never perform an update directly in the database. First pull the record from the database, then update it:

使用 Active Record 时,永远不要直接在数据库中执行更新。首先从数据库中拉取记录,然后更新它:

Model::where(['x' => 1, 'y' => 2])->first()->update([...]);

If you instead do the update directly in the database, none of the ORM functionality will trigger (such as firing events or touching parents).

如果您直接在数据库中进行更新,则不会触发任何 ORM 功能(例如触发事件或触摸父项)。

回答by Autista_z

Update all rows, which correspond conditions:

更新所有符合条件的行:

Model::where("x",1)->where("y",2)->update(array('key' => 'new_value', ...));

First row, which corresponds conditions:

第一行,对应条件:

Model::where("x",1)->where("y",2)->first()->update(array('key' => 'new_value', ...));

回答by Joel Hinz

Sure, just fetch the row and then update it as usual.

当然,只需获取该行,然后像往常一样更新它。

SomeModel::where('somecondition', 'somevalue')
         ->where('someothercondition', 'someothervalue')
         ->first()
         ->update(['somecolumn' => 'somenewvalue']);

回答by Jakhongir

Alternativly, to update table by one row at a time, method take(rows_count) can be used. Example:

或者,要一次更新一行,可以使用方法 take(rows_count)。例子:

Model::query()->where(['x' => 1, 'y' => 2])
->take(1)->update(['x' => 4, 'y' => 5]);