8月 5, 2023 - 开发笔记    laravel admin 下拉框或多选框编辑回显–使用关联的方式已关闭评论

laravel admin 下拉框或多选框编辑回显–使用关联的方式

1:分类表:category.

class Category extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'name',
        'description',
    ];

    public function productions()
    {
        return $this->hasMany(Production::class);
    }
}

2:产品表:production.

class Production extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'name',
        'description',
        'category_id',
        'method',
    ];

    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }
}

想在产品表中关联编辑选择分类:

则在productionController中

protected function form()
{
    $arr = Category::select('id','name')->get()->toArray();
    $arr = array_column($arr,'name','id');
    ksort($arr);
    $form = new Form(new Production());
    $form->text('name', __('production.name'))->rules('required');
    $form->text('description', __('production.description'));
    $form->text('method', __('production.method'));
    //单选框这个category_id是最重要的,写成其它的值(比如category)回显就不正常了
    $form->select('category_id', __('production.category_name'))->options(Category::all()->pluck('name' , 'id'))->required();
    //多选框这个category是最重要的,写成其它的值(比如category_id)回显就不正常了
    $form->multipleSelect('category', __('production.category_name'))->options(Category::all()->pluck('name' , 'id'))->required();

    $form->tools(function (Form\Tools $tools) {
        $tools->disableDelete();
        $tools->disableView();
    });

    return $form;
}

编辑时显示效果:

创建时的效果:

 

 

评论被关闭。