【问题标题】:Store array of objects in DB column. Laravel将对象数组存储在 DB 列中。拉拉维尔
【发布时间】:2018-02-19 02:35:33
【问题描述】:

试图在 DB 中存储对象数组并得到错误: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();

找到了很多答案,但没有一个有用。

更新(模型文件和迁移添加):

模型文件:

<?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();

【问题讨论】:

  • array_merge() 在哪里使用?
  • 我看到缺少 [] 括号来包裹你的数组
  • (1/1) ErrorException array_merge(): Argument #1 is not an array in HasAttributes.php (line 769) at HandleExceptions->handleError(2, 'array_merge(): Argument #1 is不是数组', '/Applications/MAMP/htdocs/ezra-app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php', 769, array('defaults' => array(' created_at', 'updated_at')))

标签: php arrays laravel object


【解决方案1】:

我假设您的 Projects 课程是一个 Eloquent 模型。根据给出的代码,尚不清楚 items 是如何映射到 MySQL 的,以及您是否告诉您的模型您想将 items 用作数组。

在您的迁移中,您可以将其设置为文本或 json 字段。例如

$table->text('items');

然后在你的模型中,你可以将它声明为一个数组:

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

现在 Laravel 的 Eloquent 模型负责在将数组存储到数据库时将其映射到字符串,反之亦然。

当您收到 array_merge 错误时,我假设您实际上是这样设置的,而 Eloquent 会在您传入字符串时导致此错误。

所以你可能可以打电话:

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

查看 Eloquent 的施法能力: Array and Json casting

【讨论】:

  • 复制了您的示例并:“数组到字符串的转换”
  • @aleXela:“数组到字符串的转换”是什么意思?
  • 如果您可以将迁移和模型代码添加到您的问题中,这将有所帮助。
  • 添加了模型和迁移
  • 你可能想设置表名protected $table = 'projects',因为你的类名是复数。来自文档:按照惯例,“snake case”,类的复数名称将用作表名,除非明确指定另一个名称。。不确定当类名是如何工作时已经是复数了。
猜你喜欢
  • 2023-03-29
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 2020-12-29
  • 1970-01-01
  • 2014-09-18
  • 2016-02-06
  • 1970-01-01
相关资源
最近更新 更多