在MySql中,我有两个表:staff
和certifications
。存在一对多关系,其中staff.pk
= certifications.fk
。
对于每个工作人员,我需要将其多个certifications.name
值插入staff
表的JSON列中。
我还需要能够将其读取为Laravel中的强制转换数组-这是否意味着它需要是JSON数组而不是JSON对象?
更新:
我需要作为批处理来执行此操作,因为我要处理成千上万条记录。这就是为什么我专注于原始SQL的原因。从性能的角度来看,实例化雄辩的模型是行不通的。
答案 0 :(得分: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
获取数据时,它将返回您数组。
希望它可以解决您的问题