Laravel5.7:如何将嵌套数组存储到数据库

时间:2019-03-08 23:19:37

标签: arrays laravel-5

使用Laravel 5.7。
设计具有许多包含表单的视图的应用。
在此视图中:
-有一个(只有一个)client_id字段。这是隐藏的,并且从url段中检索值。
-其他字段是动态的(日期,类型,注释),并涉及此客户购买的一种或多种产品。
我无法弄清楚如何将动态字段中的输入值保存到数据库中(对不起,我是编码的新手) 请参阅下面的我当前的代码和尝试。 我发现堆栈溢出中的相关答案无法使它们适合我的情况。 我会很感激

控制器中的STORE()功能

public function storeDYNarray(Request $request)
    {
        $client = $request->input('client_id');
        $all = $request->input();
        $products = $request->input('product');
        //dd($all); SEE BELOW

//THIS CREATES AS MANY NEW ENTRIES IN PRODUCTS TABLE AS NEEDED WITH THE CORRESPONDING client_ID
        foreach ($products as $product){
            $dia = new Product;
            //client_id is retrieved from an URL segment
            $dia->client_id = $request->input('client_id');
//DON'T KNOW HOW TO SAVE VALUES FROM THE DYNAMIC FIELDS
            $dia->save();
    }

我最好的镜头(很多不值得展示)

 public function storeDYNarray(Request $request)
    {
        $client = $request->input('client_id');
        $all = $request->input();
        $products = $request->input('product');
        $i=1;
        $client_products[$i] = array();

        foreach ($products as $product){
            while ($i<=count($products)){
                $client_products[$i] = new Product(array(
                    'client_id' => $client,
                    'product_date' => $products[$i]['date'],
                    'product_type' => $products[$i]['type'],
                    'product_comment' => $products[$i]['comment'],
                ));
                $client_products[$i]->save();
            }
        }
    }
}
//this returns Undefined index errors

返回dd($ all);输出

array:3 [▼
  "_token" => "uvtLaCiuAueBIuyWkoCoOTdQzYB1paxhnLw0lbyO"
  "client_id" => "898"
  "product" => array:2 [▼
    1 => array:3 [▼
      "date" => "2019-03-13"
      "type" => "new"
      "comment" => "surplus"
    ]
    2 => array:3 [▼
      "date" => "2019-03-28"
      "type" => "used"
      "comment" => "good condition"
    ]
  ]
]

产品表

class CreateProductsTable extends Migration
{
    public function up()
    {
        //KEPT VALIDATION PARAMETERS SIMPLE FOR KNOW
        Schema::create('products', function (Blueprint $table) {
            $table->increments('product_id');
            $table->string('client_id')->nullable($value = true); 
            $table->date('product_date')->nullable($value = true);
            $table->string('product_type')->nullable($value = true);
            $table->longText('comment_about_product')->nullable($value = true);
            $table->timestamps();
        });
    }

产品型号

class product extends Model
{
    //GIVEN THE STRUCTURE OF ARRAYS WHEN dd($all); I DONT THINK I NEED THAT
    /*
    public $fillable = [
        'client_id',
        'product_date',
        'product_type',
        'product_comment', 
    ];
    */

    public function client(){
        return $this->belongsTo('App\client');
        }
}

客户表

<?php
//use Illuminate...
class CreateclientsTable extends Migration
{ 
    public function up()
    {
        Schema::create('clients', function (Blueprint $table) {
            $table->string('client_id');
            $table->primary('client_id');
            //other columns...
            $table->integer('user_id')->nullable($value = true);
            $table->timestamps();
        });
    }

客户模型

class client extends Model
{
    protected $primaryKey = 'client_id';
    public $incrementing = false;
    protected $keyType = 'string';

    public function user(){
        return $this->belongsTo('App\User');
        }

    public function products(){
        return $this->hasMany('App\product');
        }
}

2 个答案:

答案 0 :(得分:0)

storeDYNarray函数中,您永远不会递增$i。并且由于您将$iwhile循环中的产品数量进行比较,因此它将永远运行。另外,除非我缺少任何内容,否则由于您正在使用while循环,因此不需要foreach循环。这是storeDYNarray函数的调整后的版本。它尚未经过测试,但有望在正确的方向上为您提供帮助:

public function storeDYNarray(Request $request)
{
    $client = $request->input('client_id');
    $products = $request->input('product');

    foreach ($products as $product) {
        Product::create([
            'client_id' => $client,
            'product_date' => $product['date'],
            'product_type' => $product['type'],
            'product_comment' => $product['comment'],
        ]);
    }
}

您还需要取消注释$fillable模型上的Product属性,以使先前的代码起作用。

答案 1 :(得分:0)

毕竟这是我使它工作的方式,不确定这是否是最好的方法,但这是可行的。

public function storeDYNarray(Request $request)


     {
            $client = $request->input('client_id');
            $all = $request->input();
            $products = $request->input('product');
            $i=1;
            while($i<=count($products)){
                $client_product[$i]=array(
                    $products[$i]['date'], //0
                    $products[$i]['type'], //1
                    $products[$i]['comment'] //2
                );
                $i++;
            }

            $i=1;
            foreach($products as $products){
                while($i<=count($diagnoses)){
                    $product = new Product;
                    $product->client_id = $client;
                    $product->product_date = $client_product[$i][0];
                    $product->product_type = $client_product[$i][1];
                    $product->product_comment = $client_product[$i][2];
                    $product->save();
                    $i++;
                }    
            }
        }

...然后我取消了模型的$ fillable属性的注释。