2015-10-21 37 views
1

我遵循Laravel文檔以及一些教程,但我必須錯過某些內容,因爲出現「列未找到」錯誤一個外鍵。我希望有人能夠指出。Laravel 5 DB Seeder外鍵「列未找到」錯誤

我認爲問題是,我不知道該怎麼「通」的ID爲試圖創建下面的一個UserDetail記錄,當我創建的每個用戶:

factory(User::class, 3) 
      ->create() 
      ->each(function($u) { 
        $u->userdetail()->save(factory(UserDetail::class)->create()); 
}); 

實際的錯誤是:

[Illuminate\Database\QueryException]                         
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' 
(SQL: update `userdetails` set `user_id` = 1 where `id` = 0) 

我的用戶表有一個自動遞增的id字段,它是userdetails表中user_id字段的外鍵。

下面是型號:

/* 
* User Model 
*/ 
class User extends Model { 
    // … 
    public function userdetail() { 
     # User has a User Detail 
     return $this->hasOne('Models\Users\UserDetail'); 
    } 
    // … 
} 

/* 
* UserDetail Model 
*/ 
class UserDetail extends Model { 
    // … 
    public function user() { 
     # UserDetail belongs to User 
     return $this->belongsTo('Models\Users\User'); 
    } 
    // … 
} 

這裏是播種機:

/* 
* UserTableSeeder 
*/ 
class UserTableSeeder extends Seeder { 
    public function run() { 
     User::truncate(); 
     UserDetail::truncate(); 

     factory(User::class, 3) 
      ->create() 
      ->each(function($u) { 
       $u->userdetail()->save(factory(UserDetail::class)->create()); 
      }); 
    } 
} 

/* 
* DatabaseSeeder 
*/ 
class DatabaseSeeder extends Seeder { 
    DB::statement('SET FOREIGN_KEY_CHECKS = 0'); // disable foreign key constraints 
    Model::unguard(); 

    $this->call('UserTableSeeder'); 

    Model::reguard(); 
    DB::statement('SET FOREIGN_KEY_CHECKS = 1'); // enable foreign key constraints 
} 

最後,示範工廠:

$factory->define(User::class, function (Faker\Generator $faker) { 
    return [ 
     'uname'  => $faker->userName, 
     'pass'  => bcrypt(str_random(8)), 
     'email'  => $faker->email, 
    ]; 
}); 

$factory->define(UserDetail::class, function (Faker\Generator $faker) { 
    return [ 
     'street' => $faker->streetName, 
     'city'  => $faker->city, 
     'state'  => $faker->stateAbbr, 
     'zip'  => $faker->postcode, 
     'phone'  => $faker->phoneNumber, 
    ]; 
}); 

感謝您的指導!

回答

0

問題在於何時分配關係。您必須使用make()方法而不是create(),因爲create()方法將使您的模型存儲在數據庫中,而make()方法只創建實例,然後save()方法將分配所需的FK並將其存儲在數據庫。

factory(User::class, 3) 
      ->create() 
      ->each(function($u) { 
        $u->userdetail()->save(factory(UserDetail::class)->make()); 
}); 
+0

它甚至不工作,如果把make()...有人做了它的工作? – ackuser