【问题标题】:inserting array value to database laravel将数组值插入数据库laravel
【发布时间】:2015-12-03 21:55:42
【问题描述】:

我有一个名为namedescriptionfeatures 的表单属性,其中features 是多个复选框,就像

feature 1
feature 2
feature 2
feature 4

用户可以一次选择多个复选框。我有一个名为product 的数据库表

-----------------------------------------
    id    name    description    features  
-----------------------------------------

当用户选择多个复选框时,我需要在功能列中插入所有复选框值。现在我可以echo选中的复选框值像

 $feat = Input::get('features');
    foreach ($feat as $key => $n){
     echo $feat[$n];
    }

但我需要将这些功能插入数据库,对于正常插入,我们会这样做:

$product = new Product;
$product->name = Input::get('name');
$product->description = Input::get('description');
$product->features = Input::get('features');
$product->save();

但是我应该如何修改上面的代码以便将数组值保存到数据库中?我正在尝试将值插入同一列,因为我不会根据功能查询它。

【问题讨论】:

  • 将数组值保存到数据库中的单列是一个非常糟糕的主意。您应该首先考虑规范化您的数据和数据结构。使用 product_feature 表之类的东西,其中,对于每个产品,您将有几行,每个特性一个。

标签: php mysql arrays laravel-5


【解决方案1】:

你可以这样插入,

$candidate_data = 数组(

            'mobile' => $request->get('mobile'),
            'password' => $request->get('password')
    );

DB::('tablename')->插入($candidate_data);

【讨论】:

    【解决方案2】:

    虽然我使用 ajax 发送值,但我有类似的东西

    <div class="row mb-3" id="insert_new_item">
    <div class="col-lg-6">
    <p>Item Description</p>
    <input value="" type="text" name="order[description]"  class="form-control product " id="" placeholder="Your Item Description">
    </div>
    <div class="col-lg-1 col-sm-6 col-12 mt-lg-0 mt-3">
        <p>Qty</p>
        <input placeholder="0" type="text" name="order[quantity]"  min="1" class="text-right form-control qty" id="" min="1">
    </div>
    <div class="col-lg-2 col-sm-6 col-12 mt-lg-0 mt-3">
        <p>Rate/Unit (&#8358; )</p>
        <input placeholder="0.00" type="text" name="order[rate]" class="text-right form-control rate" id="">
    </div>
    <div class="col-lg-2 mt-lg-0 mt-3">
        <p>Amount (&#8358; )</p>
        <input  type="text" name="order[amount]" id="" class="text-right form-control amount" readonly value="0" >
    </div>
    <div class="col-lg-1">
        <span><i class="fa fa-times text-danger  removeItem" style="font-size: 22px"></i></span>
    </div>
    

    所以当我 console.log(any value) 我得到这个:

    ["0" : "value 1", "1" : "value 2"]
    

    从我的控制器我可以做到这一点

    foreach ($request->description as $key => $description) {
        $order = Order::create([
            'description' => $description,
            'amount' => $request->rate[$key],
            'quantity' => $request->quantity[$key],
            'invoice_id' => 7
         ]);
    
    }
    

    【讨论】:

      【解决方案3】:

      请查看database normalization 了解如何存储 1:N 关系中的数据。您必须使用以下属性创建一个额外的表,例如“product_feature”:['id', 'product_id', 'function_name']。

      那么你的插入函数如下所示:

      $product = new Product;
      $product->name = Input::get('name');
      $product->description = Input::get('description');
      $product->save();
      
      $feat = Input::get('features');
      
      foreach ($feat as $key => $n){
          $product_function = new ProductFunction;
          $product_function->product_id = $product->id;
          $product_function->function_name = $feat[$n];
          $product_function->save();
      }
      

      希望对你有帮助!

      【讨论】:

      • 嘿@linx 您的方法是正确的,但在 foreach 循环中而不是 $feat[$n] 必须设置 $feat[$key] 它可以正常工作,谢谢。
      【解决方案4】:

      这很简单。如果您知道您不会查询这些特征,那么将它们存储为 Json 或序列化数组是完全可以的。但是,如果您需要查询它们并且它们是应用程序的一个关键方面,您应该将它们放在它们自己的表中。

      我更喜欢以 Json 格式存储数组,因为它更易于阅读并且不特定于 PHP。 Laravel 为您提供了很好的选择来完成这项工作。

      首先,在迁移中将products-table 的features-字段声明为json:

      Schema::create('products', function (Blueprint $table) {
          // ...
          $table->json('features');
      });
      

      然后通过简单地设置$casts-attribute 来访问数组时将Product-model 告诉automatically cast it 到一个数组:

      class Product extends Model
      {
          // ...
          protected $casts = [
              'features' => 'json'
          ];
      }
      

      就是这样。现在该数组将存储为 Json,但是当您使用 $product-&gt;features 访问它时,您将获得一个数组。

      为了让一切变得更简单,您应该在您的产品模型上设置fillable attribute

      class Product extends Model
      {
          // ...
          protected $fillable = ['name', 'description', 'features'];
      }
      

      这允许在您的控制器(或您创建产品的任何地方)中执行类似的操作:

      $product = Product::create(Input::all());
      

      ...而不是更新它并一一设置属性。

      如上所述,请确保您不需要这些功能是可查询的,这意味着您不会遇到尝试获取某些产品仅具有特定功能或其他东西的情况。但是,如果您确实需要查找特征,则应该将它们放在自己的表中。否则这种方法很好,因为它更方便。

      【讨论】:

      • 我很困惑有人说'features' =&gt; 'json',而不是'features' =&gt; 'array'。官方 laravel 文档说(甚至这个答案中的链接)“数组”是正确的,但包括这个答案在内的一些人说“json”。什么是正确的?两者都有?
      • 嘿@Arbitrary,无论是工作还是can be use synonymously,都适合你的心理模型(“将其转换为数组”与“解析此 json 数据”)
      【解决方案5】:

      您可以使用 json_encode 函数将数组保存为 json 字符串。

      $product->features = json_encode(Input::get('features'));
      

      但我也同意@AdrianBR 的观点,将数组值保存到数据库中的单个列是一个坏主意。

      【讨论】:

        猜你喜欢
        • 2018-06-16
        • 1970-01-01
        • 1970-01-01
        • 2019-04-29
        • 2019-09-26
        • 2018-01-31
        • 2015-03-29
        • 2021-10-27
        相关资源
        最近更新 更多