【问题标题】:Laravel5.7 : how to store nested arrays to databaseLaravel5.7:如何将嵌套数组存储到数据库
【发布时间】:2019-03-13 01:02:52
【问题描述】:

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

控制器中的 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');
        }
}

【问题讨论】:

    标签: arrays laravel-5


    【解决方案1】:

    在您的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'],
            ]);
        }
    }
    

    您还需要取消注释您的 Product 模型上的 $fillable 属性才能使之前的代码正常工作。

    【讨论】:

    • 嗨,这仍然给我一个“未定义的索引”错误,不知道为什么。是的,我不需要“foreach”循环和“while”循环。我很想使用“while”循环:[$i] 是字段字段的索引。根据我的 javascript 代码,当用户添加新产品时,添加的字段的索引为 2(例如:输入日期 'name' 将是 '[product][2][date]')和 ' count($products)' 是 2。你还认为它会永远运行吗?
    【解决方案2】:

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

    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 属性的注释。

    【讨论】:

      猜你喜欢
      • 2016-12-11
      • 2019-06-17
      • 2016-06-07
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      相关资源
      最近更新 更多