How to seed multiple relationships in Laravel with Faker

家住魔仙堡 提交于 2019-12-25 03:13:55

问题


I have a database with two columns, brands and shops. Each brand can owe several shops, and I want to seed my database via Fakers using Laravel.

So after setting up the migrations and the relationships in the models

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Brand extends Model
{

    /**
     * Get the shops for the brand.
     */
    public function shops()
    {
        return $this->hasMany('App\Shop','sh_brand_id');
    }
}

And:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Shop extends Model
{
    public function user() {
        return $this->belongsTo('App\Brand','sh_brand_id');
    }
}

I want to use a Factory to seed the database.

<?php

use Faker\Generator as Faker;

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

    return [
        'name' => $faker->company,
        'address' => $faker->address,
    ];
});

And

use Faker\Generator as Faker;

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

        return [
            'name' => $faker->company,
            'logo_url' => $faker->imageUrl(640, 480),
            'website' => $faker->url,
            'description' => $faker->text(500),
            'telephone_number' =>'31'. $faker->randomNumber(8),
            'principal_address' => $faker->address,
            'email' => $faker->unique()->safeEmail,
        ];
    });

And finally I need to seed the database using those Factories. There are documentation in the website and many examples for do it, but each solution I've found let me generate only one shop for each brand, and I want to generate many shops for each brands.

What is the best way to do this?


回答1:


Put it directly in your factory. I use a helper method getInstanceOf to pick a random instance of another model.

use Faker\Generator as Faker;
use App\Brand;
use App\Shop;

function getInstanceOf($class, $returnIdOnly = true) {
    $instance = $class::inRandomOrder()->first() ?? factory($class)->create();
    return $returnIdOnly ? $instance->id : $instance;
}

$factory->define(Shop::class, function (Faker $faker) {
   return [
       'name' => $faker->company,
       'address' => $faker->address,
       'sh_brand_id' => getInstanceOf(Brand::class)
   ];
});

Then when seeding,

factory(App\Brand::class, 10);
factory(App\Shop::class, 50);



回答2:


I've found this workaround that works for me:

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder {

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run() {
        factory(App\Brand::class, 50)->create() 
                ->each( 
                    function ($br) {
                        factory(App\Shop::class, 10)->create()
                                ->each(
                                    function($sh) use (&$br) { 
                                        $br->shops()->save($sh)->make();
                                    }
                                );
                    }
                );

    }
}


来源:https://stackoverflow.com/questions/49584272/how-to-seed-multiple-relationships-in-laravel-with-faker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!