在Laravel应用程序数据库中存储数组或std对象 [英] Storing array or std object in database of Laravel app

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

问题描述

数据库表将Array或stdObject存储在列中的架构是什么?

What is the schema for the database table to store Array or stdObject in a column ?

当我使用-> string并插入一个数组变量时,它仅将单词"Array"存储在db列中.

When I use ->string and insert an array variable, it only stores the word "Array" in the db column.

Laravel是否支持数组?

does Laravel has support for array?

如果没有,我应该采用什么方法?

If no, What methodology should I implement?

推荐答案

您可以将序列化的数据保存/插入到TEXT type字段中,但是为此您必须使用php进行操作,例如:

You can save/insert serialized data in to a TEXT type field but for this you have to something using php, for example:

$arr = array('x', 'y', 'z');

要将其插入数据库字段,可以使用序列化函数像这样

To insert this into a database field you can use serialize function like this

$serializedArr = serialize($arr);

现在,您可以将$serializedArr数组插入到databse中,并且在检索要使用的数据时,只需

Now, you can insert the $serializedArr array in to databse and when you retrieve the data to use, just unserialize it using somethig like:

$record = SomeModel::find(1);
unserialize($record->field_name);

您还可以使用Laravel的 accessors-and-mutators 要使整个过程自动化,请查看手册,这简直太简单了.如果您需要有关此accessors-and mutators的更多帮助,请留言并提供您的table详细信息.

Also, you can use, Laravel's accessors-and-mutators to make the whole thing automated, check the manual, it's dead simple. If you need more help on this accessors-and mutators then leave a message with your table details.

更新:

由于Laravel 5.x允许属性强制转换,因此可以将属性强制转换为用于在运行时进行转换的另一种数据类型.在这种情况下,只需声明一个protected $casts属性,例如:

Since Laravel 5.x allows attribute casting so it's possible to cast attributes to another data type for converting on runtime. In this case, just declare a protected $casts property for example:

protected $casts = [
    'is_admin' => 'boolean', // Will convarted to (Bool)
    'options' => 'array', // Will convarted to (Array)
];

array强制转换对于处理以序列化JSON存储的列特别有用.例如,如果您的数据库具有包含序列化JSON的TEXT type字段,则在您在Eloquent模型上访问该属性时,将数组强制转换为该属性将自动反序列化该属性为PHP数组,并且将值设置为此属性时,它将自动序列化回JSON,例如:

The array cast is particularly useful for working with columns that are stored as serialized JSON. For example, if your database has a TEXT type field that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model and also it'll be automatically serialized back to JSON when you set value to this property, for example:

$user = User::find(1);

// $options is an array...
$options = $user->options;

// options is automatically serialized back to JSON...
$user->options = ['foo' => 'bar'];

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

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