"Laravel中的“Array to string conversion”错误 - 尝试将数组保存到数据库"

3

抱歉,我是Laravel的新手,正在尝试第一次保存到数据库。我想把一个数组保存到数据库中,但出现了“数组转换为字符串”的错误。我已经尝试将迁移文件中的字符串值更改为其他选项,但仍然出现相同的错误。

控制器

    public function store(Request $request)
{   
    Myroutes::create([ //posting to acc table
        'start' => $request->start,
        'end' => $request->end,
        'waypoints' => $request->waypoints
    ]);

    return redirect('/');
}

迁移
 public function up()
{
    Schema::create('myroutes', function (Blueprint $table) {
        $table->increments('myroute_id');
        $table->integer('user_id');
        $table->string('start');
        $table->string('end');
        $table->string('waypoints');
        $table->timestamps();
    });
}

模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Myroutes extends Model
{
    protected $fillable = [
        'user_id',
        'start',
        'end',
        'waypoints'
    ];
}

查看

<div id="dynamicInput" class="form-group">
                    <label>Additional Destinations</label>
                    <input type="text" name="waypoints[]" class="form-control" autocomplete="on">
                </div>

数据库表

数据库表图片


航点应该是一个数组吗?你把它存储为字符串了吗? - Dave Carruthers
我之前认为我需要"waypoints[ ]"才能使谷歌地图的途经点起作用,现在我已经将其更改为只是"waypoints",但只有第一个途经点被提交到数据库。(所有上述代码仍然相同) - highfly
5个回答

3
protected $casts = [
        'theme_setting' => 'array'
];

在类中的模型中使用类型转换


2
您遇到了一个错误:'waypoints' => $request->waypoints是无法工作的,因为$request->waypoints是一个数组,您不能将数组保存到VARCHAR()字段中。如果您使用implode函数将输入转换为逗号分隔的字符串,则应该可以正常工作:
`'waypoints' => implode(",", $request->waypoints`)

话虽如此,这通常被认为是一个坏主意;考虑使用RoutesWaypoints之间的关系作为单独的表格,以便于清晰和易于使用(特别是在检索/编辑时)。


谢谢,那个有效!我不能检索航点并将每个插入到输入字段中吗? - highfly
你当然可以这样做,但是需要额外的逻辑来提取字符串、按逗号分隔等等,而不能像调用 Route->waypoints 一样检索到一个漂亮的 Waypoint 模型数组。请阅读:https://laravel.com/docs/5.6/eloquent-relationships;无论如何都是有用的知识。 - Tim Lewis
或将其保存为json字段并转换为数组。 - Indra
@Indra 绝对没错,JSON列也可以使用,只要关系型数据库管理系统支持它即可。 - Tim Lewis
“implode”和“explode”需要一个分隔符,为什么不使用“serialize”和“unserialize”将格式委托给PHP呢? - Rachel Wirtz
显示剩余2条评论

2

我在laravel 5.8中使用了这个

$array = $request->names;
$array = implode(',', $array);
$request['names'] = $array;
$distribute = User::create($request->all());

0

在表单提交后尝试执行以下操作:

dd($request->all());

然后你会看到将要被保存的内容,并且会看到waypoints是一个数组。你不能将数组保存为字符串,必须将其转换为字符串。变量是数组,因为:

name="waypoints[]"

如果你这样写,它就不会是一个数组:

name="waypoints"

我曾经担心谷歌地图的途经点名称没有方括号会无法工作。我将其删除后,它仍然可以正常工作,但现在只有第一个途经点提交到数据库中,因为我将其改回了 'waypoints' => $request->waypoints - highfly

-1

你的表单输入 "waypoints" 是一个数组!因此,在进行插入之前,你需要先进行“转换”。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接