2016-09-06 63 views
4

Laravel 5.3,PHP 5.6 新鲜laravel new项目,最小配置。Laravel ORM数组到字符串转换

我做了一个简单的迁移和模型,并试图通过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从工厂传单它应该做的:

>>> factory('App\Foo')->make(); 
=> App\Foo {#696 
    foo: "[email protected]", 

但是,当我尝试击中数据库时,Eloquent无法将第e查询值中的一个字符串:

>>> $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 ([email protected], 2016-09-06 23:59:03, 2016-09-06 23:59:03))' 

在Google上没有这样的内容。有任何想法吗?

(编辑显示相同的问题,一个更简单的例子)

+1

你确定这不是因为你没有设置对模型的可填写字段? – pseudoanime

+0

@pseudoanime刚刚添加了$ fillable字段(上面已编辑)。同样的结果。 –

回答

1

解决了它。问题是faker库。显然,当您明确投出(string)$faker->whatever它可以解决问题。

7

某些faker方法将其结果作为数组返回,作为默认值。例如:

$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')