[英]Store array of objects in DB column. Laravel
試圖在數據庫中存儲對象數組並出現錯誤: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();
我假設您的Projects
類是一個雄辯的模型。 使用給出的代碼,尚不清楚如何將items
映射到MySQL,以及是否告訴模型是否要將items
用作數組。
在遷移中,您可以將其設置為text或json字段。 例如
$table->text('items');
然后在模型中,可以將其聲明為數組:
protected $casts = [
'items' => 'array',
];
現在,Laravel的口才模型負責將數組存儲到數據庫時將其映射到字符串,反之亦然。
當您遇到array_merge錯誤時,我假設您實際上是通過這種方式進行設置的,而Eloquent在傳遞字符串時會導致此錯誤。
因此,您可能可以致電:
$tmp->items = [["id" => "108124505876479", "name" => "Wakeboarding"],["id" => ... ... ]];
請參閱Eloquent的轉換功能: 數組和Json轉換
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.