尝试在DB中存储对象数组并收到错误:array_merge():参数#1不是数组
$tmp = new Projects;
$tmp->items = '{"id":"108124505876479","name":"Wakeboarding"},{"id":"112003352149145","name":"Bouldering"},{"id":"110008522357035","name":"Handball"}';
$tmp->save();
找到了很多答案,但没有人有用。
更新(添加了模型文件和迁移):
模型文件:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Projects extends Model
{
protected $casts = [
'items' => 'array',
];
}
迁移文件:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProjectsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('gID', 100);
$table->string('name', 100);
$table->text('items');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('projects');
}
}
和功能:
$tmp = new Projects;
$tmp->name = "aaa";
$tmp->gID = "FLSKJDF3R23R";
$tmp->items = [["id" => "108124505876479", "name" => "Wakeboarding"],["id" => "aa", "name" => "volkswagen" ]];
$tmp->save();
答案 0 :(得分:0)
我假设您的Projects
课程是一个雄辩的模型。使用给出的代码,不清楚items
如何映射到MySQL以及您是否告诉模型您要将items
用作数组。
在迁移中,您可以将其设置为text或json字段。 E.g。
$table->text('items');
然后在您的模型中,您可以将其声明为数组:
protected $casts = [
'items' => 'array',
];
现在,Laravel的Eloquent Model在将数组存储到数据库时将数组映射到字符串,反之亦然。
当你收到array_merge错误时,我假设你实际上是这样设置的,当你传入一个字符串时,Eloquent会导致这个错误。
所以你可以打电话:
$tmp->items = [["id" => "108124505876479", "name" => "Wakeboarding"],["id" => ... ... ]];
参见Eloquent的施法能力: Array and Json casting