的array
数据类型是不存在于所有的数据库系统,并且由于Laravel的架构构建的数据库无关,它不提供方法来创建非普通数据类型的列。所以你有两个选择:
1.使用原始的SQL语句来添加列,就像我认为应该工作的语句。通过使用attribute casting
DB::statement('ALTER TABLE pickups ADD COLUMN shifts integer[]');
2.用雄辩的可用的解决方法:虽然我不知道,如果查询生成器或机锋能正确处理这些类型的列。在您的迁移创建列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
]
谢谢@Bogdan为您的答案,不幸的是,当我尝试创建新的皮卡条目与''班'=> [1,5 ,7],'我收到这个错误信息'PHP警告:preg_replace():参数不匹配,模式是字符串,而替换是数组'。 –
好吧现在它的工作方式就像''shift'=>'[1,5,7]',',谢谢:) –
我已经测试了这个干净的安装Laravel 5.1,对我来说它实际上没有放置引号在分配值时在数组周围。 – Bogdan