首页 > 解决方案 > laravel 背包中的可重复字段

问题描述

如何添加可重复字段以使用添加电话添加多个电话号码和地址,使用 laravel 背包添加地址选项?

我有 3 个表(人、电话、地址表)

address 和 phone 表与 person 表有关系

我想使用文本字段接受姓名,使用可重复字段接受电话号码和地址,并将姓名保存在人员表中,电话号码分别保存在电话表和地址表中。

     $this->crud->addField([   
        'name'  => 'Landline',
        'label' => 'Phone Numbers',
        'type'  => 'repeatable',
        'fields' => [
            [
                'name'    => 'Landline',
                'type'    => 'text',
                'label'   => 'Phone Number',
                'wrapper' => ['class' => 'form-group col-md-12'],
            ],
       ,
        ],
        'new_item_label'  => '+Add Phone', 

      ]);
   

      $this->crud->addField([   
        'name'  => 'person_addresses', // belongsTo relation
        'label' => 'Adresses',
        'type'  => 'repeatable',
        'pivot' => true,
        'fields' => [
            [
              'label' => 'Region',
              'type' => 'select',
              'name' => 'region_id',
              'attribute' =>'region', 
              'entity' => 'region',
              'wrapper'   => [ 
              'class' => 'form-group col-md-4'],
            ],
            [
              'label' => 'City/Subcity',
              'type' => 'select',
              'name' => 'city_id',
              'attribute' =>'city', 
              'entity' => 'city', 
              'allows_null' => true,
              'model' => 'App\Models\city',
              'wrapper'   => [ 
              'class' => 'form-group col-md-4'],
          ],
          [
            'name' => 'location_pin',
            'type'=> 'address_algolia',
            'label' => "Location Pin",
            'wrapper'   => [ 
              'class' => 'form-group col-md-4'
            ],
        ],
          
        ],
        'new_item_label'  => 'Add Address', 
      ]);
          

标签: laravel-backpack

解决方案


默认情况下,可重复字段将该信息作为 JSON 存储在数据库中。

如果您希望它以另一种方式存储,我建议您使用假名(例如联系人)创建该字段,然后

  • 在您的模型中创建一个修改器(例如 setContactAttribute($value)),它将解析该数组并将其存储在适当的表/关系中;
  • 在您的模型中创建一个访问器(例如 getContactAttribute),它将从关系中获取信息并以相同的数组格式返回它;

推荐阅读