我可以使用 eloquent/fluent 按最大 ID 更新单行吗
Can I update a single row by maximum id using eloquent/fluent
我有以下查询:
$row = Notification::where('from_user_id', '=', Auth::id())
->where('to_user_id', 0)->update(['to_user_id' => $obj]);
哪个有效,但我如何只更新一行?我希望使用最大 ID,例如 ->max('id')
,但我尝试了多种实现方式,但我没有运气。或者我可以使用时间戳来区分唯一性吗?
id|from_user_id|to_user_id |created_at|updated_at
1 | 8 | 0 |2015-04-09|2015-04-09
2 | 8 | 0 |2015-04-09|2015-04-09
我实际上是在遍历我的 $obj
变量,所以它发生变化只是因为它是数组的一部分,这就是为什么我只想更新其中一行的原因。
您在第二个 where 子句和更新值必须是数组类型时缺少“=”符号,查询应该是
$row = Notification::where('from_user_id', '=', Auth::id())
->where('to_user_id','=', 0)->update(array('to_user_id' => $obj));
可以得到最后一行(基于created_at字段):
$row = Notification::where('from_user_id', '=', Auth::id())
->where('to_user_id', 0)
->orderBy('created_at', 'desc')
->first();
并更新该行的 to_user_id
:
$row->to_user_id = YOUR_TO_USER_ID;
$row->save();
我有以下查询:
$row = Notification::where('from_user_id', '=', Auth::id())
->where('to_user_id', 0)->update(['to_user_id' => $obj]);
哪个有效,但我如何只更新一行?我希望使用最大 ID,例如 ->max('id')
,但我尝试了多种实现方式,但我没有运气。或者我可以使用时间戳来区分唯一性吗?
id|from_user_id|to_user_id |created_at|updated_at
1 | 8 | 0 |2015-04-09|2015-04-09
2 | 8 | 0 |2015-04-09|2015-04-09
我实际上是在遍历我的 $obj
变量,所以它发生变化只是因为它是数组的一部分,这就是为什么我只想更新其中一行的原因。
您在第二个 where 子句和更新值必须是数组类型时缺少“=”符号,查询应该是
$row = Notification::where('from_user_id', '=', Auth::id())
->where('to_user_id','=', 0)->update(array('to_user_id' => $obj));
可以得到最后一行(基于created_at字段):
$row = Notification::where('from_user_id', '=', Auth::id())
->where('to_user_id', 0)
->orderBy('created_at', 'desc')
->first();
并更新该行的 to_user_id
:
$row->to_user_id = YOUR_TO_USER_ID;
$row->save();