在 Laravel 应用程序的数据库中存储数组或 std 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21658926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:44:02  来源:igfitidea点击:

Storing array or std object in database of Laravel app

arrayslaraveleloquent

提问by rgb

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

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

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

当我使用 ->string 并插入一个数组变量时,它只在 db 列中存储单词“Array”。

does Laravel has support for array?

Laravel 是否支持数组?

If no, What methodology should I implement?

如果不是,我应该采用什么方法?

回答by The Alpha

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

您可以将序列化数据保存/插入到TEXT类型字段中,但为此您必须使用某些东西php,例如:

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

To insert this into a database field you can use serializefunction like this

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

$serializedArr = serialize($arr);

Now, you can insert the $serializedArrarray in to databse and when you retrieve the data to use, just unserializeit using somethig like:

现在,您可以将$serializedArr数组插入到数据库中,当您检索要使用的数据时,只需使用以下内容对其进行反序列化

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

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

此外,您可以使用 Laravel 的访问器和修改器使整个过程自动化,查看手册,这非常简单。如果您需要更多帮助,accessors-and mutators请留下您的table详细信息。

Update:

更新:

Since Laravel 5.xallows attribute castingso it's possible to cast attributes to another data type for converting on runtime. In this case, just declare a protected $castsproperty for example:

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

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

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

array投是与系列化是存储列工作特别有用JSON。例如,如果您的数据库有一个TEXT包含序列化 JSON的类型字段,则将数组强制转换添加到该属性将PHP在您在Eloquent模型上访问该属性时自动将其反序列化为一个数组,并且它会JSON在您设置时自动序列化回此属性的值,例如:

$user = User::find(1);

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

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

回答by Yevgeniy Afanasyev

The best way since Laravel 5.1 is to CAST your table field like this:

自 Laravel 5.1 以来最好的方法是像这样 CAST 你的表字段:

class Mytable extends Model
{
    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'my_field' => 'array',
    ];

Read more about attribute casting on official documents pageof Laravel. The quote:

在Laravel 的官方文档页面上阅读更多关于属性转换的信息。报价单:

The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast, while the value is the type you wish to cast to the column to. The supported cast types are: integer, real, float, double, string, boolean, object, array, collection, date and datetime.

模型上的 $casts 属性提供了一种将属性转换为常见数据类型的便捷方法。$casts 属性应该是一个数组,其中键是被转换的属性的名称,而值是您希望转换为列的类型。支持的转换类型有:整数、实数、浮点数、双精度、字符串、布尔值、对象、数组、集合、日期和日期时间

The only limitationthat docs does not say is that you cannotwork with this array directly, like this

文档没有说的唯一限制是你不能直接使用这个数组,像这样

$myTable.my_field[]='new array element';

instead, you have to prepare array separately and then assign it to the field, like this:

相反,您必须单独准备数组,然后将其分配给字段,如下所示:

$temp=[];
$temp[]='new array element';
$myTable.my_field[]=$temp;

If you use older version of Laravel, please use an answer providerd by The Alpha, or even better, quit your job :).

如果您使用旧版本的 Laravel,请使用The Alpha提供的答案,或者更好的是,请辞掉工作:)。