如何将数组保存在一个列中?

时间:2019-07-18 01:42:24

标签: mysql laravel

我的数据库中有下表。

Schema::create('projects', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->string('url');
    $table->string('requirements');
    $table->string('coverImage');
    $table->string('domain');
    $table->text('feedbacks');
    $table->text('technologies_id');
    $table->timestamps();
});

我想在我的technologies_id中放入一个数组,例如:

technologies_ids: [1,2,3]

我尝试了以下方法。

$project = new Project;
$project->title = $request->title;
$project->url = $request->url;
$project->requirements = $request->requirements;
$project->coverImage = $request->coverImage;
$project->customer_id = $request->customer_id;
$project->domain = $request->domain;
$project->feedbacks = $request->feedbacks;
$project->technologies_id = json_encode($request->technologies_id);
$project->services_id = $request->services_id;

错误

  

数组到字符串的转换(SQL:插入projects

3 个答案:

答案 0 :(得分:3)

在项目模型中添加

protected $casts=['technologies_id'=>'array']

删除json_encode

$project->technologies_id = $request->technologies_id;

并在您的刀片文件中

technologies_id必须是复选框中的数组,或选择

 name="technologies_id[]"

存储数据时,从数据库获取数据时将自动进行编码和解码

在文档中阅读

https://laravel.com/docs/5.8/eloquent-mutators#array-and-json-casting

答案 1 :(得分:0)

您可以序列化数组,使其可以是字符串。

$technologies_id = serialize(json_encode($request->technologies_id);

然后,如果要再次将其转换为数组,请使用unserialize($array)

希望有帮助!

答案 2 :(得分:0)

将数据存储在列中时,请使用implode()

$project->technologies_id = implode(",",$request->technologies_id);

然后,当您从列中获取或获取数据时,请使用explode()

$project = Project::find(1);
$techonolgy_ids = explode(',',$project->technologies_id);