模型关联
class Food extends BaseModel
{
use HasDateTimeFormatter;
use SoftDeletes;
public function images(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(FoodImage::class, 'food_id', 'id');
}
}
class FoodImage extends Model
{
use HasDateTimeFormatter;
protected $table = 'food_images';
protected $fillable = ['path', 'food_id'];
const UPDATED_AT = null;
public function food()
{
return $this->belongsTo(Food::class, 'id', 'food_id');
}
}
表单
$form->multipleImage('images')->sortable()->compress(['width' => 750, 'quality' => 90,])->uniqueName()->saveAsString()
->saving(function ($value) use ($form) {
if ($form->isEditing() && request()->filled('_file_del_')) {
// 编辑页面,删除图片逻辑
if (FoodImage::where('path', request()->input('_file_del_'))->delete()>0){
return $form->response()->success('删除成功');
}
return $form->response()->error('删除失败');
}else{
// 新增或编辑页面上传图片
if ($value) {
$data = json_decode($value);
$model = FoodImage::whereIn('path', $data)->delete(); // 删除全部
$insert_data = [];
foreach ($data as $val) {
$insert_data[] = [
'path' => $val,
'food_id' => $form->model()->id,
'created_at' => Carbon::now()->toDateTimeString()
];
}
\DB::table('food_images')->insert($insert_data); // 重新添加
}
return $form->response()->success('成功');
}
})->customFormat(function ($v) { // 转换为显示的格式
if (! $v) {
return;
}
return array_column($v, 'path');
});