简体   繁体   中英

Store array of objects in DB column. Laravel

Trying to store array of objects in DB and getting an error : array_merge(): Argument #1 is not an array

$tmp = new Projects;
$tmp->items = '{"id":"108124505876479","name":"Wakeboarding"},{"id":"112003352149145","name":"Bouldering"},{"id":"110008522357035","name":"Handball"}';
$tmp->save();

Found a lot of answers, but no one is useful.

Update (model file and migration added):

Model file:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Projects extends Model
{
    protected $casts = [
        'items' => 'array',
    ];

}

Migration file:

<?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');
    }
}

and the function:

$tmp = new Projects;
$tmp->name = "aaa";
$tmp->gID = "FLSKJDF3R23R";
$tmp->items = [["id" => "108124505876479", "name" => "Wakeboarding"],["id" =>  "aa", "name" => "volkswagen" ]];
$tmp->save();

I'm assuming your Projects class is an Eloquent Model. With the code given, it is not clear how items is mapped to MySQL and whether you told your model that you want to use items as an array.

In your migration, you can set it to be a text or json field. Eg

$table->text('items');

Then in your model, you can declare it as an array:

protected $casts = [
    'items' => 'array',
];

Now Laravel's Eloquent Model takes care of mapping your array to a string when it gets stored to the DB and vice versa.

As you get an array_merge error, I assume you actually set it up this way and Eloquent causes this error, as you pass in a string.

So you probably can just call:

$tmp->items = [["id" => "108124505876479", "name" => "Wakeboarding"],["id" => ... ... ]];

See Eloquent's casting capabilities: Array and Json casting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM