dcat-admin multipleImage实现多图关联上传

本文介绍了如何在 Laravel 中使用 Eloquent ORM 对 Food 和 FoodImage 模型进行关联操作,包括 HasMany 和 belongsTo 关系,以及表单中文件上传和删除的处理逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模型关联

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');
                });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值