创建父级时创建模型(例如,在创建用户时创建5个帖子)

时间:2016-03-19 18:18:47

标签: php laravel laravel-5

如果用户有很多帖子,且帖子属于用户,则操作起来很简单:

$factory->define(App\Post::class, function ($faker) {
    return [
        'title' => $faker->title,
        'content' => $faker->paragraph,
        'user_id' => function () {

            // Creates a User for every Post
            return factory(App\User::class)->create()->id;
        }
    ];
});

我如何完成相反的事情?相反,在创建用户时创建5个帖子并将该帖子与新创建的用户相关联?

〜编辑 我正在使用laravel 5.2,并且我已经在我的模型中声明了我的模型关系,所以我现在有:

$user = factory(App\User::class)->create();
$posts = factory(App\Post::class, 3)->make();
$user->posts()->saveMany($posts);

// Great, now I have a User and 3 Posts associated with that user. 


// However, now, I want let's say, 5 votes per post.
// I can't call $posts->votes(), so I iterate

foreach ($posts as $post) { 
    $votes = factory(App\Votes::class, 5)->make();
    $post->votes()->saveMany($votes);
}

然后任何其他与投票等的关系都会嵌套在foreach中。

2 个答案:

答案 0 :(得分:2)

我会使用模型事件。在AppServiceProvider中,添加如下事件:

namespace App\Providers;

use App\User;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        User::created(function ($user) {
            $posts = factory(App\Post::class, 3)->make();
            $user->posts()->saveMany($posts);
        });

        Post::created(function ($post){
            $votes = factory(App\Vote::class, 3)->make();
            $post->votes()->saveMany($votes);
        });
    }

现在您不必担心自动创建,此外,这不应该是Controller逻辑的一部分。

答案 1 :(得分:1)

$factory->define(App\User::class, function ($faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->email
    ];
});

$factory->define(App\Post::class, function ($faker) {
    return [
        'title' => $faker->title,
        'content' => $faker->paragraph
    ];
});


$user = factory(User::class)->create();

$post = factory(User::class)->create();

$用户>帖() - >准($交);

$posts

中创建5个fakers
$posts = factory(App\Post::class, 3)->make();
$user->posts()->saveMany($posts);