在Laravel 5.6中存储数组 [英] Store array in Laravel 5.6

查看:71
本文介绍了在Laravel 5.6中存储数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从输入中跟随数组

I have to following array from inputs

array:9 [
  "columns" => "4"
  "device_id" => array:4 [
    0 => "1"
    1 => "2"
    2 => "3"
    3 => "4"
  ]
  "hub_id" => "11"
  "usage" => array:4 [
    0 => "1"
    1 => "2"
    2 => "3"
    3 => "4"
  ]
   ....

在我的 foreach 循环中,我仅返回一个值,而不是全部

In my foreach loop i get back only one value not all

$devices = $request->all();    
foreach ($devices["device_id"] as $device) {
           dd($device);
}

这只会返回 1 一个值,而不是全部.

This will return only 1 one value not all.

我在显示所有值并将其保存到数据库时遇到问题.女巫会是快速正确的方法吗?

I have problem displaying all the value and saving them to database. Witch would be the fast and the right way ?

推荐答案

您不将数组保存在数据库中.数据库不应保存多维结构,因为它们不支持多维结构.

You do not save array in a database. Databases are not supposed to save multidimensional structures, since they do not support them.

您必须将数组转换为数据库能够保存的格式,例如JSON或PHP序列化.如果您以后不必再轻易地搜索数据,以这种方式保存数据实际上是很常见的.

You must convert your array into a format that the database is able to save, for example JSON or PHP serialize. It is actually very common to save data in this way if you do not need to search it easily at a later time.

尽管如此,我还是会在您的模型中使用setter来实现:

Nevertheless, I would use a setter in your model to achieve this:

public function setAttributeNameAttribute($values)
{
    $this->attributes['attribute_name'] = json_encode($values);
}

public function getAttributeNameAttribute($values)
{
    return json_decode($values);
}

这篇关于在Laravel 5.6中存储数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆