2014-01-17 73 views
4

我正在使用faker類來幫助播種我的數據庫。該DatabaseSeeder看起來像這樣在laravel中播種時的質量分配錯誤

<?php 

class DatabaseSeeder extends Seeder 
{ 
public function run() 
{ 
    Eloquent::unguard(); 

    $tables = [ 
     'users', 
     'posts', 
    ]; 

    foreach ($tables as $table) { 
     DB::table($table)->truncate(); 
    } 

    $this->call('UsersTableSeeder'); 
    $this->call('PostsTableSeeder'); 
    } 
} 

和UsersTableSeeder

<?php 

class UsersTableSeeder extends Seeder { 

public function run() 
{ 
    $faker = Faker\Factory::create(); 

     for($i=0 ; $i<50 ; $i++) { 
     $user = User::create([ 
      'first_name'   => $faker->firstName, 
      'surname'   => $faker->lastName, 
      'email'    => $faker->email, 
      'username'   => $faker->userName, 
      'bio'    => $faker->sentences, 
      'bio_html'   => $faker->sentences, 
      'wesbite'   => $faker->url, 
      'twitter'   => $faker->word, 
     ]); 
    } 
    } 
} 

我收到以下錯誤在終端當我嘗試和種子此表。

[Illuminate\Database\Eloquent\MassAssignmentException] 
first_name  

如果我嘗試和種子都我得到這個

[ErrorException]                  
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array 

我想包括Eloquent::unguard();停止了這個錯誤?我正在運行最新版本的Laravel。

回答

2

您可以在模型中定義保留字段的空數組;

class User extends Eloquent 
{ 
    protected $guarded = []; 
} 
+0

如果'DatabaseSeeder'類調用'Eloquent :: unguarded()',該解決方案爲何會有所幫助? – mike

+0

它幫助了我。我使用單個播種機獲得相同的錯誤。 – klauskpm

11

faker->sentences()faker->paragraphs()回報陣列和類預計將收到的字符串。

您可以使用faker->text(),或者你可以你可以使用

implode(" ",$faker->sentences()); 
+1

來到這裏傻眼了,這是我的解決方案!謝謝! –

2

好吧,我想你只需要在你的DatabaseSeeder.php做簡單的,就像這樣:

public function run() 
{ 
    Eloquent::unguard(); 

    $this->call('UsersTableSeeder'); 
    $this->call('PostsTableSeeder'); 
} 

您的UsersTableSeeder.php,如下所示:

<?php 

use Faker\Factory as Faker; 

class UsersTableSeeder extends Seeder { 

    public function run() 
    { 
    $faker = Faker::create(); 

    for($i=0 ; $i<50 ; $i++) { 
     $user = User::create([ 
     'first_name'   => $faker->firstName, // try using str_random(10) 
     'surname'   => $faker->lastName, // try using str_random(20) 
     'email'    => $faker->email, 
     'username'   => $faker->userName, // $faker->unique()->userName 
     'bio'    => $faker->sentences, 
     'bio_html'   => $faker->sentences, 
     'wesbite'   => $faker->url, 
     'twitter'   => $faker->word, 
     ]); 
    } 
    } 
} 

而且,在你的模型,user.php的,添加:

protected $guarded = []; 

我在這裏執行和兩個工作:

php artisan db:seed 
php artisan db:seed --class=UsersTableSeeder 

我配置laravel和攤販,在作曲家,像這樣的:

"require": { 
    "laravel/framework": "4.2.*", 
    "fzaninotto/faker": "dev-master" 
}, 

希望它能幫助你。