[英]How to remove/update single value from array in the database in laravel 6?
Currently I have a column called userIds
in my database which is an array.目前,我的数据库中有一个名为
userIds
的列,它是一个数组。 I want to be able to update/remove a single value from that array but the methods I have tried has not worked.我希望能够从该数组中更新/删除单个值,但我尝试过的方法没有奏效。
Controller控制器
public function removeUser(Request $request) {
$scrumId = $request->scrumId;
$userId = $request->userId;
DB::table('scrumboards')->where('userIds', $userId)->delete();
return redirect()->back();
}
How would I be able to update a single value from an array from the database without removing the entire column?如何在不删除整个列的情况下更新数据库中数组中的单个值?
--EDIT-- - 编辑 -
DB row example:数据库行示例:
title UserIds
test ["1"]
It's really bad idea to use userIds
.使用
userIds
真的很糟糕。 If your scrumboards
datas become huge.如果您的
scrumboards
数据变得巨大。
It will become so slow when find the scrumboards with userid
.当找到带有
userid
的 scrumboards 时,它会变得很慢。
so Why don't you use hasMany
or many-to-many
relationship, like Scrumboard
has many Users
所以你为什么不使用
hasMany
或many-to-many
关系,就像Scrumboard
有很多Users
and if your datas become huge, you can add index to scrumboard_id
,如果您的数据变得巨大,您可以向
scrumboard_id
添加索引,
Scrumboard Model:计分板模型:
class Scrumboard extends Model {
protected $table = 'scrumboards';
public function users()
{
return $this->hasMany(User::class, 'scrumboard_id', 'id');
}
}
User Model:用户模型:
class User extends Model {
protected $table = 'users';
public function scrumboard()
{
return $this->belongsTo(Scrumboard::class, 'scrumboard_id');
}
}
and then you can delete like this:然后你可以像这样删除:
User::where('id', $userId)->delete();
# or
User::where('id', $userId)->update(['scrumboard_id' => null]);
If you really want to use user_ids, you can do it like this: (find the user_id by like
, update it to empty by replace
)如果你真的想使用user_ids,你可以这样做:(通过
like
找到user_id,通过replace
其更新为空)
$sb = DB::table('scrumboards')->where('userIds', 'like', "%\"{$userId}\"%");
$sb->update(['userIds' => \DB::raw("REPLACE(userIds, '\"{$userId}\"', '')")]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.