MySql 更新查询以插入 JSON 值

标签 mysql arrays json laravel

在 MySql 中,我有两个表:staffcertifications。存在一对多关系,其中 staff.pk = certifications.fk

对于每位员工,我需要将其多个 certifications.name 值插入到 staff 表中的 JSON 列中。

我还需要能够将其读取为 Laravel 中的数组转换 - 这是否意味着它需要是 JSON 数组,而不是 JSON 对象?

更新:

我需要以批处理的方式执行此操作,因为我有数千条记录需要处理。这就是为什么我专注于原始 SQL。从性能角度来看,实例化 Eloquent 模型是行不通的。

最佳答案

您可以使用访问器和修改器

namespace App;
use Illuminate\Database\Eloquent\Model;

class Staff extends Model
{
    //assuming you have certificates column in staff table to store json data

    public function setCertificatesAttribute($certificates)
    {
        $this->attributes['certificates'] = json_encode($certificates);
    }

    public function getCertificatesAttribute()
    {
        if($certificates != null){
           return json_decode($certificates, true); //force to array
        }

        return []; //default empty array
    }
}

Now if you create or update staff

Staff::create([
     'name' => 'Staff1',
     'certificates' => ['certificate1', 'certificate2'] 
]);

然后它会自动保存为json数据到你的员工表中。当您使用 $staff->certificates 获取数据时,它将返回您的数组。

希望能解决您的问题

关于MySql 更新查询以插入 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51039181/

相关文章:

c# - 将字符串解析为 int 数组

json - 合并从wordpress导出的两个Json文件

json - Node 和 express 发送 json 格式

mysql - 如何在mysql中获取记录 ORDER BY user_id DESC ANDcreated_date ASE

ruby - 如何对多个数组的对应元素求和?

c# - 二维数组的行和列大小

javascript - 从 JSON 列表响应对象属性获取第一段文本

php - 你能帮我根据我的 mysql 查询在 php 中构建 json 吗?

php - mysql_insert_id 和 last_insert_id 错误行为

MySQL 表被标记为崩溃