工厂厂房返回的company_id和package_id相同

时间:2018-08-30 04:07:39

标签: model laravel-5.6 factories

在我的代码中,每个公司都属于一个程序包,并且具有程序包用法 class Package扩展了Model。 包型号:

protected $fillable =[
    'name',
    'daily_cv_view',
    'monthly_cv_view',
    'per_job_post_cv_view',
    'active_job_post_limit',
    'question_per_job_post_limit',
    'package_lifetime',
    'job_post_lifetime_limit',
    'price'
    ];
public function companies()
{
    return $this->hasMany('App\Models\Company');
}

public function packageUsages()
{
    return $this->hasMany('App\Models\package_usage');
}

公司型号

 public function package()
    {
        return $this->belongsTo('App\Models\Package', 'package_id');
    }

packageUsage模型

public function company()
    {
        return $this->belongsTo('App\Models\Company');
    }
    public function package()
    {
        return $this->belongsTo('App\Models\Package');
    }

在我的数据库播种机中,我正在尝试为每个创建的公司构建一个软件包。所以看起来像这样:

 $companies=factory(App\Models\Company::class, 20)->create()->each(function ($company) {
            $company->users()->save(factory(App\Models\User::class)->make());
            $company->events()->save(factory(\App\Models\Event::class)->make());
        });
        foreach ($companies as $company)
            $company->packageUsages()->save(factory(\App\Models\PackageUsage::class)->make([
                'company_id'=>$company->id,
                'package_id'=>$company->first()->package_id
            ]));

最后是我的步调用法虚幻的画面:

$factory->define(App\Models\PackageUsage::class, function (Faker $faker) {
    $companyId= $faker->randomElement(\App\Models\Company::all()->pluck('id')->toArray());
    $company= App\Models\Company::find($companyId);
    $package=$company->package;
    $dailyCvView=$package->first()->daily_cv_view;
    return [
        'company_id'=>$company,
        'package_id'=>$package,
        'daily_cv_view'=>$faker->numberBetween($min=0 , $max=$dailyCvView ),
        'monthly_cv_view'=>$faker->numberBetween($min=$dailyCvView , $max=$package->monthly_cv_view ),
        'active_job_post_count'=>$company->jobPosts->count(),
        'expiration_date'=>$faker->dateTimeBetween($min='now', $max='+ 30 days')
    ];
});

公司工厂:

$factory->define(\App\Models\Company::class, function (Faker $faker) {
        return [
        'name'=>$faker->company,
        'company_size'=>$faker->randomElement(['10','50','100','200']),
        'slogan'=>'باما کار کنید',
        'website'=>$faker->domainName,
        'logo'=>'/images/companies/avatar',
        'message_title'=>'ما در اینجا.....',
        'message_content'=>$faker->paragraph('10'),
        'main_photo'=>'/images/companies/mainphotos/avatar',
        'about_us'=>$faker->paragraph('10'),
        'why_us'=>$faker->paragraph('10'),
        'recruiting_steps'=>$faker->paragraph('10'),
        'address'=>$faker->address,
        'email'=>$faker->safeEmail,
        'phone_number'=>$faker->numberBetween(10,100),
        'location'=>$faker->city,
            'package_id'=>$faker->randomElement(\App\Models\Package::all()->pluck('id')->toArray())
    ];
});

当我运行它时,它返回错误:

   Illuminate\Database\QueryException  : SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`balatar`.`package_usages`, CONSTRAINT `package_usages_package_id_foreign` FOREIGN KEY (`package_id`
) REFERENCES `packages` (`id`)) (SQL: insert into `package_usages` (`company_id`, `package_id`, `daily_cv_view`, `monthly_cv_view`, `active_job_post_count`, `expiration_date`, `updated_at`, `created_at`) values (4, 4, 12, 484, 0, 2018-09-16 07:26:11, 2018-08-30
 03:45:22, 2018-08-30 03:45:22))

当我检查数据库时,我发现它为每个公司ID和软件包ID都创建了3个软件包。因为我认为当它尝试使用两个ID为4且仅插入3个程序包来构建它时,第四个外键失败。 我的代码有什么问题?

1 个答案:

答案 0 :(得分:1)

我认为您的第一个错误是在数据库设计中。您的公司将有一个以上的软件包,据我了解,当时只有一个有效的软件包。因此,需要在companiespackages表之间创建多对多关系,如下所示:

Schema::create('rel_company_package', function (Blueprint $table) {
    $table->increments('id');
    $table->timestamps();
    $table->unsignedInteger('package_id');
    $table->unsignedInteger('company_id');
    $table->timestamp('activated_at')->nullable();
    $table->timestamp('expires_at')->nullable();
    $table->boolean('is_active')->nullable();
    $table->unsignedInteger('nubmer_of_remaining_job_posts');
});
  1. actived_at:您的公司激活其软件包的日期。
  2. nubmer_of_remaining_job_posts:首先来自您的包裹数据,并且在公司发布工作后将减少一。
  3. expires_at:包裹过期的时间
  4. is_active:此字段是多余的,但将帮助您花费更多的内存而不是计算资源。将确定当前分配的软件包是否处于活动状态
  

注意:您应该在决定激活该软件包后立即用适当的值填写activated_atexpires_atis_active

     

此外,您还应该在软件包分配时填写nubmer_of_remaining_job_posts

您决定要播种的日志数据是您可能不依赖的生产时间,因为它很容易变得庞大,并且需要大量资源来计算所需的内容。顺便说一句,日志数据(PackageUsage)应该只保留数据透视表的(rel_company_packageid

直接返回您的错误:

首先,在您的company factory中加载所有程序包并随机选择一个(而package usage factory是),最好不要这样做,而是要求MySQL为您随机选择一个程序包

对于随机公司:

$company = $\App\Models\Company::query()->inRandomOrder->first();
// and use $company->id

对于随机包装:

$package = \App\Models\Package::query()->inRandomOrder()->frist();
// and use $package->id

另一点是,您应该创建一个PackageUsage实例,如下所示:

$company->packageUsages()->save(factory(\App\Models\PackageUsage::class)->make([
    'package_id' => $company->first()->package_id
]));

它不需要再次传递company_id。似乎您错过了packageUsages()模型中的Company方法,它应该是:

public function packagesUsage() 
{
    return $this->hasMany('\App\Models\PackageUsage', 'company_id')
}

您可能会因键入错误而将comapny_id替换为package_id

但是正如我最初提到的,您最好首先修复您的结构。