如何在Laravel中添加工厂关系

时间:2016-04-28 05:36:05

标签: php laravel-5.2

我有两个模型

  

艺术家

     

相册

我正在尝试编写一个工厂来像这样种植数据库

$factory->define(App\Artist::class, function (Faker\Generator $faker) {
    return [
        'artist_name' => $faker->name($gender = null|'male'|'female'),
        'followers'    => $faker->randomDigitNotNull(),
        'artist_image'=>$faker->imageUrl($width = 256, $height = 256), 
        'artist_title' =>$faker->word(4),
        'artist_address' =>$faker->address(),
        'artist_phone' =>$faker->phoneNumber(),
        'artist_fb' =>$faker->sentence(4),
        'artist_description' => $faker->paragraph()
    ];
});

$factory->define(App\Album::class, function (Faker\Generator $faker) {
    return [
    'album_name' => $faker->company(),
    'album_art' => $faker->imageUrl($width = 263, $height = 292),
    'album_description' => $faker->paragraph($nbSentences = 3, $variableNbSentences = true),
    'album_mainart' => $faker->imageUrl($width = 1140, $height = 1140),  
    'album_soundcloud' => $faker->company(),
    'album_youtube' => $faker->company(),
    'artist_id' => factory(App\Artist::class)->create()->id,
    ];
});

和在DatabaseSeeder.php我喜欢这个

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
         Model::unguard();
         //DB::table('artists');
       // factory(App\Artist::class, 50)->create();

        factory(App\Artist::class, 10)
           ->create()
           ->each(function($u) {
                $u->posts()->save(factory(App\Album::class)->make());
            });

          Model::reguard();
    }
}
执行

php artisan db:seed

错误

  

调用未定义的方法Illuminate \ Database \ Query \ Builder :: posts()

任何想法如何做到这一点

谢谢

0 个答案:

没有答案