现在的业务中需要一个用户上传四种不同类型的图片, 都是多张, 所以我新建了一个多态的图片表保存用户的图片地址
user表:
id
images表:
id
imagetable_type
imagetable_id
imagetable_sub_type
用户模型:
<?php
class User {
/**
* @return MorphMany|Image
*/
public function degreePictures()
{
return $this->morphMany(Image::class, 'imagetable')->degree();
}
/**
* @return MorphMany|Image
*/
public function educationPictures()
{
return $this->morphMany(Image::class, 'imagetable')->education();
}
}
图片模型中:
<?php
class Image {
public function scopeDegree(Builder $builder)
{
return $this->scopeOfSubType($builder, self::SUB_TYPE_DEGREE);
}
public function scopeEducation(Builder $builder)
{
return $this->scopeOfSubType($builder, self::SUB_TYPE_EDUCATION);
}
}
这样在查询的时候可以简单的通过动态属性获取到列表, 但是在插入的时候 imagetable_sub_type
只能通过多次的循环手动插入, 不是很方便
$doctor->qualificationPictures()->delete();
$doctor->qualificationPictures()->createMany(collect($request->input('qualification_picture'))
->map(function ($item) {
return array_merge($item, ['imagetable_sub_type' => Image::SUB_TYPE_QUALIFICATION]);
})->all());
不知道 Laravel 里面有没有便捷的方法处理这种情况?