繁体   English   中英

从Laravel中的数组插入表

[英]Inserting into a table from the array in laravel

我从视图中获取此数组

当我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, 
foreach ($BlogData['Tag'] as $x) 
{
    Tag::create(['Tag' => $x]);
}

对于Model :: create(),参数必须为array。 您传递了一个值而不是数组。 请看看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);
}
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插入多行的好方法的好链接

使用雄辩的ORM在Laravel中批量插入

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM