如何使用laravel工厂将数据添加到相关表中?

如何使用laravel工厂将数据添加到相关表中?,laravel,laravel-factory,Laravel,Laravel Factory,在laravel 8应用程序中,我为带有工厂的ads表添加了虚拟数据: $ads = Ad::factory()->count(10)->expired($year, $month)->create([ ]); 使用数据库/factories/AdFactory.php: <?php namespace Database\Factories; use Config; use Carbon\Carbon; use App\Models\Ad; use Illumina

在laravel 8应用程序中,我为带有工厂的ads表添加了虚拟数据:

$ads = Ad::factory()->count(10)->expired($year, $month)->create([
]);
使用数据库/factories/AdFactory.php:

<?php

namespace Database\Factories;

use Config;
use Carbon\Carbon;
use App\Models\Ad;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
use \Cviebrock\EloquentSluggable\Services\SlugService;

class AdFactory extends Factory
{
    protected $model = Ad::class;

    public function definition()
    {
        $text= $this->faker->text;
        $slugValue = SlugService::createSlug(Ad::class, 'slug', $text);

        return [
            'title' => $text,
            'ad_token' => $text,
            'slug' => $slugValue,
            'phone_display' => (rand(1, 3) == 1),
            'has_locations' => (rand(1, 4) == 1),
            'status' => 'A',
            'price' => mt_rand(10, 500),
            'ad_type' => (rand(1, 2) == 1 ? 'B' : 'S'),
            'description' => $this->faker->paragraphs(rand(1, 4), true),
            'creator_id' => rand(1, 5),
        ];
    }

    public function expired($year, $month)
    {
        return $this->state(function (array $attributes) use($year, $month) {
            $dateStr= $year.'-'.str_pad($month, 2, "0", STR_PAD_LEFT).'-01';
            $startDate= Carbon::createFromFormat('Y-m-d', $dateStr);
            return [
                'expire_date' => $this->faker->dateTimeInInterval($startDate, '1 month', Config::get('app.timezone'))->format('Y-m-d H:i:s')
            ];
        });
    }
}

您可以创建CategoryFactory类并创建虚拟类别,然后选择一个随机类别作为类别id

一对多关系

/。。。
公共功能定义()
{
返回[
//你的代码
'creatory_id'=>this->faker->randomElement(Category::all())['id'],
];
}
//...

公共函数定义()
{
返回[
//你的代码
'creatory_id'=>factory(Category::class)->create()->id,
];
}
第二个解决方案将为每个广告创建一个新类别

多对多关系

名称空间数据库\工厂;
使用App\Models\AdFactory;
使用App\Models\Category;
使用Illumb\Database\Eloquent\Factorys\Factory;
使用light\Support\Str;
类AdFactory扩展了工厂
{
/**
*工厂对应型号的名称。
*
*@var字符串
*/
受保护的$model=Ad::class;
/**
*配置模型工厂。
*
*@return$this
*/
公共函数配置()
{
返回$this->afterCreating(函数(Ad$newAd){
$adCategory=adCategory::factory()->count(1)->create(['ad_id'=>$newAd->id,'category_id'=>$this->faker->randomElement(category::all())['id']);
}); 
}
// ...
}
欲了解更多信息,请访问


您可以创建CategoryFactory类并创建虚拟类别,然后选择一个随机类别作为类别id

一对多关系

/。。。
公共功能定义()
{
返回[
//你的代码
'creatory_id'=>this->faker->randomElement(Category::all())['id'],
];
}
//...

公共函数定义()
{
返回[
//你的代码
'creatory_id'=>factory(Category::class)->create()->id,
];
}
第二个解决方案将为每个广告创建一个新类别

多对多关系

名称空间数据库\工厂;
使用App\Models\AdFactory;
使用App\Models\Category;
使用Illumb\Database\Eloquent\Factorys\Factory;
使用light\Support\Str;
类AdFactory扩展了工厂
{
/**
*工厂对应型号的名称。
*
*@var字符串
*/
受保护的$model=Ad::class;
/**
*配置模型工厂。
*
*@return$this
*/
公共函数配置()
{
返回$this->afterCreating(函数(Ad$newAd){
$adCategory=adCategory::factory()->count(1)->create(['ad_id'=>$newAd->id,'category_id'=>$this->faker->randomElement(category::all())['id']);
}); 
}
// ...
}
欲了解更多信息,请访问


您的示例不清楚。什么是“creatory_id”?我将详细说明:对于ads表,我还有带有id、名称字段的categories表。我需要将虚拟数据添加到ad_类别(字段ad_id、category_id),其中ad_id-REF指向新创建的广告,category_id-REF指向现有类别中的一个。谢谢!哦,我以为这是一对多的关系。但是你可以将广告关联到一个随机的虚拟类别。对不起,不清楚。请给我举个例子好吗?我不知道如何获取和使用NewlyAd.id?谢谢!我通过一些修复代码实现了这一点:return$this->afterCreating(函数(Ad$newAd){//Ad model在这里返回$adCategory=adCategory::factory()->count(1)->create(['Ad_id'=>$newAd->id,'category_id'=>$this->faker->randomElement(category::all())['id'],];);请编辑它,我将接受您的答案!@mstdmstd Done!您的示例不清楚。什么是“创建者id”?我将详细说明:对于ads表,我还有带有id、名称字段的类别表。我需要将虚拟数据添加到ad_类别(字段ad_id、类别id),其中ad_id-REF指向新创建的广告,category_id-REF指向现有类别中的一个。谢谢!哦,我以为这是一对多的关系。但是你可以将广告关联到一个随机的虚拟类别。对不起,不清楚。请给我举个例子好吗?我不知道如何获取和使用NewlyAd.id?谢谢!我通过一些修复代码实现了这一点:return$this->afterCreating(函数(Ad$newAd){//Ad model在这里返回$adCategory=adCategory::factory()->count(1)->create(['Ad_id'=>$newAd->id,'category_id'=>$this->faker->randomElement(category::all())['id'],];);请编辑它,我会接受你的答案!@mstdmstd Done!