Laravel 8 工厂的多重关系

wiz*_*zeb 6 php laravel laravel-factory

在 Laravel 8 中,可以快速填充与工厂的关系。但是,我不知道如何生成多个关系。如何使用新的 Laravel 8 语法为每个链接创建随机或新的关系?

此工厂语法仅在 Laravel 8 中可用。 https://laravel.com/docs/8.x/database-testing#factory-relationships

问题

考虑以下关系:

  • 每个链接都属于一个网站和一个帖子。
  • 网站和帖子都可以有很多链接。
<?php

class Post extends Model
{
    use HasFactory;

    function links()
    {
        return $this->hasMany(Link::class);
    }
}

class Website extends Model
{
    use HasFactory;

    function links()
    {
        return $this->hasMany(Link::class);
    }
}

class Link extends Model
{
    use HasFactory;

    function post()
    {
        return $this->belongsTo(Post::class);
    }

    function website()
    {
        return $this->belongsTo(Website::class);
    }
}

Run Code Online (Sandbox Code Playgroud)

我尝试过/想要什么

我下面尝试的只会为所有链接生成一个模型。如何使用新的 Laravel 8 语法为每个链接创建随机或新的关系?

Link::factory()->count(3)->forPost()->forWebsite()->make()

=> Illuminate\Database\Eloquent\Collection {#4354
     all: [
       App\Models\Link {#4366
         post_id: 1,
         website_id: 1,
       },
       App\Models\Link {#4395
         post_id: 1, // return a different ID
         website_id: 1,
       },
       App\Models\Link {#4370
         post_id: 1, // return a different ID
         website_id: 1, // return a different ID
       },
     ],
   }
Run Code Online (Sandbox Code Playgroud)

And*_*kiy 5

只需将其添加到您的LinkFactory

  public function definition()
  {
    return [
        'post_id' => function () {
            return Post::factory()->create()->id;
        },

        .....
    ];
}
Run Code Online (Sandbox Code Playgroud)

现在您可以为每个新链接创建新帖子:

Link::factory()->count(3)->create();//Create 3 links with 3 new posts
Run Code Online (Sandbox Code Playgroud)

或将新链接附加到现有帖子:

Link::factory()->count(3)->create(['post_id' => Post::first()->id]); //create 3 links and 0 new posts
Run Code Online (Sandbox Code Playgroud)


jed*_*jed 1

laravel 魔法工厂方法for允许您使用外部表中的一条记录填充数据库。请参阅文档链接https://laravel.com/docs/8.x/database-testing#belongs-to-relationships

在您的情况下,使用forPost()andforWebsite()将允许您使用 Post 表和 Website 表中的一个 id 填充数据库。

如果您想使用不同的 ID,请改用此语法 Link::factory()->count(3)->make()