【问题标题】:MySql Update Query to insert JSON valuesMySql 更新查询以插入 JSON 值
【发布时间】:2018-12-04 22:57:11
【问题描述】:

在 MySql 中,我有两个表:staffcertificationsstaff.pk = certifications.fk 是一对多的关系。

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

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

更新:

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

【问题讨论】:

  • 您已经在staffcertifications 之间建立了一对多的关系,那么为什么要将证书存储在员工表中?
  • @rkj,我需要进行提取,因为我正在从几十个表中创建一个临时数据缓存并将其传递给前端应用程序。

标签: mysql arrays json laravel


【解决方案1】:

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

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
    }
}

现在,如果您创建或更新人员

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

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

希望它能解决你的问题

【讨论】:

  • 查看 OP 中的更新
  • @KimPrince 你不能使用Staff::insert($staffs);DB::table('staffs')->insert($staffs); 进行批处理操作
猜你喜欢
  • 2019-04-03
  • 2011-08-29
  • 2017-08-15
  • 2014-07-21
  • 2017-04-23
  • 1970-01-01
  • 1970-01-01
  • 2014-02-09
  • 1970-01-01
相关资源
最近更新 更多