在laravel中从数组插入表中

时间:2015-02-10 01:48:52

标签: php laravel laravel-4 eloquent

我从视图中获取此数组

当我做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, 

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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

对于create方法,您必须在模型中使用$ fillable数组

protected $fillable = [
    'Tag'
];

在您的控制器中

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

答案 2 :(得分:0)

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