laravel 数组到字符串的转换(SQL:insert into

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49904696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:39:24  来源:igfitidea点击:

Array to string conversion (SQL: insert into

phpmysqllaravelseeding

提问by Ber Tsacianegu del Tepuy

I'm trying to insert data from a Seeder in Laravel 5.6 and I'm having a problem with the field that is json type. I want this field ('stops') to be an array (for example of ten integers not repeated).

我正在尝试从 Laravel 5.6 中的 Seeder 插入数据,但我遇到了 json 类型字段的问题。我希望这个字段('stops')是一个数组(例如不重复的十个整数)。

The table seeder (RoutesTableSeeder.php) is something like this:

表播种器 (RoutesTableSeeder.php) 是这样的:

<?php

 use \Illuminate\Support\Facades\DB;
 use Illuminate\Database\Seeder;
 use Faker\Factory as Faker;

 use App\Models\Route;

 class RoutesTableSeeder extends Seeder
 {
   /**
   * Run the database seeds.
   *
   * @return void
   */
   public function run()
   {
    //factory(Route::class, 20)->create();

    $faker = Faker::create();

    //$values= array();

    /*for($i=0; $i < 10; $i++) {
        $values []= $faker->unique()->randomDigit;
    }

    print_r(json_encode($values));*/

    foreach (range(1, 20) as $index)
    {
        $values = array();

        for($i=0; $i < 10; $i++) {
            $values []= $faker->unique()->randomDigit;
        }

        //print_r($values);

        DB::table('routes')->insert([
            'user_id' => $faker->numberBetween($min = 1, $max = 20),
            'name' => $faker->name,
            'description' => $faker->name,
            'route_photo' => $faker->image($dir = null, $width = 640, $height = 480, $category = null, $fullPath = true, $randomize = true, $word = null),
            'stops'=> [
                        //$values,
                        json_encode($values)
                        //implode(", ", $values)
            ],
        ]);
    }

  }
  }

I tried several ways to insert data. When I use json_encode($values) I have the following error:

我尝试了几种插入数据的方法。当我使用 json_encode($values) 时,出现以下错误:

Array to string conversion 
(SQL: insert into `routes` (`user_id`, `name`, `description`, `route_photo`, `stops`) 
values (19, Isaac 
  Feil, Holly Nolan, /tmp/bc8a3cf5e015d3afa96317485499e0ca.jpg, 
[8,6,0,7,3,1,5,2,4,9]))

This kind of value [8,6,0,7,3,1,5,2,4,9] is what I want to store in 'stops' field, for example, but I don't know what is going wrong....

例如,这种值 [8,6,0,7,3,1,5,2,4,9] 是我想存储在 'stops' 字段中的值,但我不知道出了什么问题....

Please, would you be so kind to help me? I'm desperate....

拜托,你会这么好心帮助我吗?我很绝望....

I post the model if it helps:

如果有帮助,我会发布模型:

<?php

  namespace App\Models;

  use Illuminate\Database\Eloquent\Model;

  class Route extends Model
    {
      protected $fillable = [
       'user_id',
       'name',
       'description',
       'route_photo',
       'stops'
 ];


   protected $casts = [
    'stops' => 'array'
  ];
 }

And the migration:

和迁移:

  public function up()
{
    Schema::create('routes', function (Blueprint $table) {
        $table->increments('id');
        //FK:users
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
        //FK:users
        $table->string('name');
        $table->string('description')->nullable();
        $table->string('route_photo');
        $table->json('stops');
        $table->timestamps();
    });
 }

Thanks a lot!!

非常感谢!!

回答by Barmar

json_encode($values)returns a string, which you can use as the value of the stopscolumn. There's no need to put []around it, that creates an array, and you can't store an array directly into a column. Just leave out the brackets:

json_encode($values)返回一个字符串,您可以将其用作stops列的值。没有必要[]围绕它创建一个数组,并且您不能将数组直接存储到列中。只需省略括号:

'stops' => json_encode($values)

However, storing arrays in database columns is generally a bad idea, it violates normalization principles. You should use a separate table with a row for each value.

但是,将数组存储在数据库列中通常是一个坏主意,它违反了规范化原则。您应该使用一个单独的表格,每个值都有一行。

回答by Niklesh Raut

Don't cast stopsto array, First remove

不要投射stops到数组,首先删除

protected $casts = [
    'stops' => 'array'
];

And use json_encodeto make string

并用于json_encode制作字符串

'stops'=> json_encode($values),