【问题标题】:Laravel ORM Array to String ConversionLaravel ORM 数组到字符串的转换
【发布时间】:2017-01-14 12:12:51
【问题描述】:

Laravel 5.3、PHP 5.6 新鲜的laravel new 项目,最低配置。

我做了一个简单的迁移和模型,并试图通过php artisan tinker 将数据植入其中。

我的迁移如下所示:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatesFooTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('foo', function (Blueprint $table) {
            $table->increments('id');
            $table->string('foo', 20);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('foo');
    }
} 

当我运行 php artisan migrate 时,数据库填充得很好。

对应的模型很简单:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Foo extends Model
{
    protected $table = 'foo';

    protected $fillable = ['foo'];

}

我也有一个 ModelFactory:

$factory->define(App\Foo::class, function (Faker\Generator $faker) {

    return [
        'foo' => $faker->email,
    ];
});

当我尝试 make 工厂传单时,Tinker 做了我认为应该做的事情:

>>> factory('App\Foo')->make();
=> App\Foo {#696
     foo: "morgan39@gmail.com",

但是当我尝试访问数据库时,Eloquent 无法将查询值包装在字符串中:

>>> $foo = factory('App\Foo')->create();
Illuminate\Database\QueryException with message 'SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'foo' at row 1 (SQL: insert into `foo` (`foo`, `updated_at`, `created_at`) values (jakayla62@streich.org, 2016-09-06 23:59:03, 2016-09-06 23:59:03))'

Google 上没有类似的东西。有什么想法吗?

(已编辑以使用更简单的示例显示相同的问题)

【问题讨论】:

  • 您确定不是因为您没有在模型上设置可填写字段吗?
  • @pseudoanime 刚刚添加了 $fillable 字段(上面已编辑)。结果相同。

标签: php laravel orm eloquent


【解决方案1】:

默认情况下,一些伪造方法将其结果作为数组返回。例如:

$faker->words(3)

会返回:

array('porro', 'sed', 'magni')

要将结果作为字符串返回,您可以将true 作为某些方法的第二个参数传递,如上一个使用words 方法的示例:

$faker->words(3, true)

返回:

"porro sed magni"

readme中所述:

words($nb = 3, $asText = false)    // array('porro', 'sed', 'magni')

【讨论】:

    【解决方案2】:

    解决了。问题是faker库。显然,当您显式转换 (string)$faker-&gt;whatever 时,它可以解决问题。

    【讨论】:

      猜你喜欢
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      • 2012-01-10
      • 2016-09-02
      • 1970-01-01
      • 2020-09-10
      • 2018-05-10
      相关资源
      最近更新 更多