gpt4 book ai didi

php - Laravel迁移数组类型(数据库列存储数组)

转载 作者:IT王子 更新时间:2023-10-29 01:24:20 26 4
gpt4 key购买 nike

我想在我的表中存储一个整数数组,但在 Documentation 中找不到任何支持数组的类型,任何建议。

迁移:

public function up()
{
Schema::create('pickups', function (Blueprint $table) {
$table->increment('id');
$table->boolean('default');
$table->integer('shifts'); <<--------- HERE I want to store an array of integers
$table->integer('status_id');

$table->timestamps();
});
}

最佳答案

array 数据类型并非存在于所有数据库系统中,并且因为 Laravel 的 Schema Builder 与数据库无关,它不提供创建非常见数据类型列的方法。所以你有两个选择:

1. 使用原始 SQL 语句来添加列,类似于下面的语句,我认为应该可以。虽然我不确定 Query Builder 或 Eloquent 是否可以正确处理这些类型的列:

DB::statement('ALTER TABLE pickups ADD COLUMN shifts integer[]');

2. 通过使用 attribute casting 来使用 Eloquent 的可用解决方法.在您的迁移中,将列创建为 json,如下所示:

public function up()
{
Schema::create('pickups', function (Blueprint $table) {
$table->increment('id');
$table->boolean('default');
$table->json('shifts');
$table->integer('status_id');

$table->timestamps();
});
}

然后你可以设置你的 Pickup 模型(如果你还没有这样做的话)并使用 $casts 属性:

class Pickup extends Model
{
protected $casts = [
'shifts' => 'array'
];
}

这会让 Eloquent 知道,当它从数据库中获取数据时,它必须将 shifts 列的值转换为 array。这只是模拟一个实际的数组,因为在数据库级别,列的类型是 TEXT 并且数组是序列化的。但是,当反序列化列值时,Eloquent 会返回一个实际的整数数组供您在代码中使用。下面是一个示例用例:

// Create a new Pickup entry
$pickup = App\Pickup::create([
'default' => true,
'shifts' => '[1, 5, 7]', // you can easily assign an actual integer array here
'status_id' => 1
]);

假设当您稍后检索条目时,上面生成了一个 id 等于 1 的条目:

$pickup = App\Pickup::find(1);
dump($pickup->shifts);

上面代码中的 dump() 将输出一个实际的整数数组:

array:3 [▼
0 => 1
1 => 5
2 => 7
]

关于php - Laravel迁移数组类型(数据库列存储数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32954424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com