【问题标题】:Inserting into a table from the array in laravel从laravel中的数组插入表
【发布时间】:2015-02-10 01:48:52
【问题描述】:

我正在从视图中获取这个数组

当我做return $BlogData['Tag'];

结果是

 ["1", "2"]

如何将其插入每条记录,即表中的新条目?

S.No | Tag
   3 |  1
   4 |  2

如上表所示

当我尝试时

foreach ($BlogData['Tag'] as $x) 
        {
        echo $x;
        Tag::create($x);
        }

我收到了这个错误

message: "Argument 1 passed to Illuminate\Database\Eloquent\Model::create() must be of the type array, string given, 

【问题讨论】:

  • 我认为消息已经很清楚了,您可以解决,

标签: php laravel laravel-4 eloquent


【解决方案1】:
foreach ($BlogData['Tag'] as $x) 
{
    Tag::create(['Tag' => $x]);
}

【讨论】:

    【解决方案2】:

    对于 Model::create(),参数必须是数组。您传递了一个值而不是数组。请看http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_create

    对于创建方法,您必须在模型中添加 $fillable 数组

    protected $fillable = [
        'Tag'
    ];
    

    在你的控制器中

    $data = $BlogData['Tag'];
    foreach ($data as $key=>$value)
    {  $data_attribute = array('Tag'=>$value);
       Tag::create($data_attribute);
    }
    

    【讨论】:

      【解决方案3】:
      foreach ($BlogData['Tag'] as $x) 
      {
          # Tag index will be the table column name
          # and its value is $x
          $pass = array(
              'Tag' => $x
          );
          Tag::create($pass);
      }
      

      这是插入多行的好方法的好链接 使用 laravel

      Bulk Insertion in Laravel using eloquent ORM

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-19
        • 2017-09-20
        • 1970-01-01
        • 2015-11-06
        • 2021-07-25
        • 2016-09-15
        • 1970-01-01
        • 2020-10-20
        相关资源
        最近更新 更多