在不以 JSON 格式 Laravel 保存数据的情况下以可重复方式加载数据时出现问题 - 背包

Problem loading data in repeatable without saving data in JSON format Laravel-Backpack

我用的是repeatable, from Laravel-Backpack 我可以把数据保存到两个表里。但是,我无法在尝试编辑销售时加载这些数据。它不会加载通过 Repeatable 保存的表单中的数据。

示例:

通过link查看演示示例时。 https://demo.backpackforelaravel.com/admin/dummy/create 它将来自 REPEATABLE 字段的数据转换为 JSON,并保存在数据库中名为 Extra.

的字段中

数据库中额外字段的保存格式:

{
 "simple": "[{\"text\":\"TesteTesteTesteTeste\",\"email\":\"admin@admin\",\"textarea\":\"teste\",\"number\":\"1\",\"float\":\"1\",\"number_with_prefix\":\"1\",\"number_with_suffix\":\"0\",\"text_with_both_prefix_and_suffix\":\"1\",\"password\":\"123\",\"radio\":\"1\",\"checkbox\":\"1\",\"hidden\":\"6318\"}]",
}

在我的例子中,我在不使用 JSON.

的情况下将数据保存在不同的表中
//My Model
class Sales extends Model

    protected $casts = [
        'id' => 'integer',
        'user_id' => 'integer',
        'date_purchase' => 'date',
        'client_id' => 'integer',
    ];

    public function getProductsAttribute()
    {

        $objects = ItensProducts::where('product_id', $this->id)->get();
        $array = [];

        if (!empty($objects)) {
            foreach ($objects  as $itens) {
                $obj = new stdClass();
                $obj->product_id = "" . $itens->product_id;
                $obj->quantity  = "" . $itens->quantity;

                $categoryProduct = CategoryProduct::where('product_id',  $itens->product_id)->get();

                  $arrayCategoryProduct = [];
                foreach ($categoryProduct  as $stItens) {
                    $arrayCategoryProduct[] = $stItens->name;
                }
                $obj->categories_product = $arrayCategoryProduct;

                $array[] = $obj;
            }
        }
        //Converts JSON to the example of the extra database field 
        $array_result = json_encode(\json_encode($array), JSON_HEX_QUOT | JSON_HEX_APOS);
        $array_result = str_replace(['\u0022', '\u0027'], ["\\"", "\'"], $array_result);

        return $array_result;
    }

我的表格:

//SalesCruController.php
protected function setupCreateOperation()
    {
        CRUD::addField([   // repeatable
            'name'  => 'products',
            'label' => 'Produtos(s)',
            'type'  => 'repeatable',
            'fields' => [
                [
                    'name' => 'product_id', 'type' => 'select2', 'label' => 'Produtos',
                    'attribute' => "name",
                    'model' => "App\Models\Product",
                    'entity' => 'products',
                    'placeholder' => "Selecione o Produto",
                    'wrapper'  => [
                        'class' => 'form-group col-md-6'
                    ],
                ],
                [
                    'name' => 'category_id', 'type' => 'select2', 'label' => "Categoria",
                    'attribute' => "name",
                    'model' => "App\Models\CategoryProduct",
                    'entity' => 'categories',
                    'placeholder' => "Selecione uma Categoria",
                ],
                [
                    'name'  => 'quantity',
                    'label' => "Quantidade",
                    'type'  => 'text',
                ],
            ],
            // optional
            'new_item_label'  => 'Adicionar',
            'init_rows' => 1,
            'min_rows' => 1,
            'max_rows' => 3,

        ],);
    }
}

方法存储

public function store()
    {
        $item = $this->crud->create($this->crud->getRequest()->except(['save_action', '_token', '_method']));

        $products = json_decode($this->crud->getRequest()->input('products'));

        $this->validateRepeatableFields($categoryProduct);

        if (is_array($products)) {

            foreach ($products  as $itens) {

                $obj = new ItensProduct();
                $obj->sale_id =  $item->getKey();
                $obj->product_id = $itens->product_id;
                $obj->quantity  = $itens->quantity;
                $obj->save();

                $categoryProduct = json_decode($itens->categories);

                foreach ($categoryProduct  as $cItens) {
                    $objCat = new CategoryProduct();
                    $objCat->product_id = $obj->getKey();
                    $objCat->name = $cItens;
                    $objCat->save();
                }
            }
        } else {
            \Alert::add('warning', '<b>Preencha os campos de pelo menos um produto.</b>')->flash();
            return redirect('admin/sales/create');
        }
        \Alert::success(trans('backpack::crud.insert_success'))->flash();
        return redirect('admin/sales');
    }

function validateRepeatableFields($categoryProduct)
{
    foreach ($categoryProduct as $group) {
        Validator::make((array)$group, [
            'sale_id' => 'required',
            'product_id' => 'required',
            'quantity' => 'required',
        ], [
            "product_id.required" => "O campo Produto é obrigatório",
            "quantity.required" => "O campo quantidade é obrigatório",
        ])->validate();
    }
}

我能够解决return将字段转换为可重复表单的问题。

如果有人需要,我想分享解决方案。当我尝试将 category_id 字段中的数据放入 json 中时发生错误,它必须像这样 return,如下所示。

{"product_id": "4", 数量: "3", "category_id": "[10, 4, 8, 8]"}

向量必须在字符串内,我正在传递字段但没有将整个向量转换为可重复项预期格式的字符串。然后我承认了字符串中的 ID,最后我承认了 cohets 并使用子字符串删除了最后一个 virgulation,如下面的代码所示。

通过这种方式,我能够 return 具有以可重复形式保存在数据库中的适当信息的字段。

     public function getProductsAttribute()
    {
        $objects = ItensProducts::where('product_id', $this->id)->get();
        $response = [];
    
        if (!empty($objects)) {
            foreach ($objects as $itens) {
    
                $categoryProduct = CategoryProduct::where('product_id', $itens->product_id)->get();
    
                $itensCatProd = '';
                foreach ($categoryProduct as $itensCatProd) {
                    $itensCatProd .= $itensCatProd->id . ',';
                };
    
                $response[] = [
                    'product_id' => $itens->product_id,
                    'category_id' => '[' . substr($itensCatProd, 0, -1) . ']',
                    'quantity' => $itens->quantity,
                ];
    
                return json_encode($response);
            }
        }
    }