2016-11-28 69 views
0

大家谁是试图帮助,laravel工厂插入的外键

我尝试创建工厂文件播我的数据库和我有一个问题,我怎么可以插入从表的外键已经播种? 和工厂代码是全部在同一个文件?这有什么好的做法?

文件

型号用户

<?php 

namespace App\Models; 

use Illuminate\Foundation\Auth\User as Authenticatable; 

class User extends Authenticatable 
{ 

    protected $table = 'user'; //name of the table in database 
    protected $primaryKey = 'Id'; //Primary Key of the table 

    /** 
    * Relations between tables 
    */ 
    public function GetLoginInfo() 
    { 
    return $this->hasMany('App\Models\LoginInfo', 'UserId'); 
    } 

    public function getStatus() 
    { 
    return $this->belongsTo('App\Models\AccountStatus'); 
    } 

} 

示范帐户状态

<?php 

namespace App\Models; 

use Illuminate\Database\Eloquent\Model; 

class AccountStatus extends Model 
{ 
    protected $table = 'account_status'; //name of the table in database 
    protected $primaryKey = 'Id'; //primary Key of the table 
    public $timestamps = false; //true if this table have timestaps 
    /** 
    * Relations between tables 
    */ 
    public function GetUsers() 
    { 
    return $this->hasMany('App\Models\Users', 'StatusId'); 
    } 
} 

出厂文件:

<?php 
/** @var \Illuminate\Database\Eloquent\Factory $factory */ 

//Factory for Account Status table 
$factory->define(App\Models\AccountStatus::class, function (Faker\Generator $faker) { 
    return [ 
     'Description' => $faker->word, 
    ]; 
}); 

//Factory for user table 
$factory->define(App\Models\User::class, function (Faker\Generator $faker) { 
    return [ 
     'Username' => $faker->unique()->userName, 
     'Password' => bcrypt('test'), 
     'Email' => $faker->unique()->safeEmail, 
     'Name' => $faker->name, 
     'StatusId' => Factory(App\Models\AccountStatus::class)->create()->id, 
    ]; 
}); 

这是我尝试做的,你可以看到:工厂(应用程序\型号\ AccountStatus ::类) - >创建() - > ID,但不工作

回答

2
$factory->define(App\Models\User::class, function (Faker\Generator $faker) { 
    return [ 
     'Username' => $faker->unique()->userName, 
     'Password' => bcrypt('test'), 
     'Email' => $faker->unique()->safeEmail, 
     'Name' => $faker->name, 
     'StatusId' => factory(App\Models\AccountStatus::class)->create()->id, 
    ]; 
}); 

我看到一个大写的F工厂..

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

    $accountStatus = factory(App\Models\AccountStatus::class)->create() 

    return [ 
     'Username' => $faker->unique()->userName, 
     'Password' => bcrypt('test'), 
     'Email' => $faker->unique()->safeEmail, 
     'Name' => $faker->name, 
     'StatusId' => $accountStatus->id, 
    ]; 
}); 
+0

工作,但我发现另一种方式,这种方式我总是创建一个新帐户状态这样我得到一个随机已经为我的例子创建更好 “StatusId” => \软件\型号\ AccountStatus ::所有() - >随机() - >标识, – syszen