使用模型工厂一对一和&定义Laravel外键.一对多关系而无需创建不必要的模型 [英] Defining Laravel foreign keys with Model Factories, One to One & One to Many Relationships without creating unnecessary models

查看:105
本文介绍了使用模型工厂一对一和&定义Laravel外键.一对多关系而无需创建不必要的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我一直在尝试通过Model Factories和Faker使用Laravel播种为数据库播种.

Recently I have been trying to seed my database using Laravel seeding through Model Factories and Faker.

对于简单的模式,让它工作起来很容易:).但是,在处理涉及外键和表关系的复杂数据库架构时,我遇到了几个问题:

For simple schemas, it is just a breeze to have it working :). However, I have encountered several problems when working with complex DB schemas which involve foreign keys and table relationships:

  • 一对一
  • 一对多
  • 多对多

...就像链接中描述的那样: 模型工厂中的Laravel 5.1外键.

...Like the one described in the link: Laravel 5.1 foreign keys in model factory.

在本主题中,官方文档建议运行数据库像这样的种子:

In this topic, the official documentation suggests to run the database seeds like this:

public function run()
{
    factory(App\User::class, 50)->create()->each(function ($u) {
        $u->posts()->save(factory(App\Post::class)->make());
    });
}

...但是这种解决方案存在一个问题:在处理许多数据库表并运行许多种子(它们之间具有许多关系)时,通常使用这种方法创建许多不必要的模型方法.例如,如果我们在上述示例之一之前运行PostsTableSeeder.php,则所有这些帖子都不会链接到用户,并且永远不会在测试和开发中使用...

... but there is one problem with this solution: when working with many DB tables and running many seeds (with many relations between them), it is common to create many unnecessary models using this methodology. For instance, if we had run the PostsTableSeeder.php before the one of the above example, all those posts would not have been linked to users, and would never be used in tests and development...

因此,在寻找一种解决这种情况的方法时,我想出了一个对我有用的功能解决方案,避免了不必要地创建那些孤立"模型……

So searching for a way to handle this situation, I have come up to a functional solution that works for me and avoids the unnecessary creation of those 'orphan' models...

我想与所有人共享它,因此答案中有对它的解释:).

And I wanted to share it with everyone, so it is just explained in the answer :).

推荐答案

所以这是我的解决方案:

So here is my solution:

该示例处理:

  • 用户和个人资料(用于说明一对一关系)
  • 用户和帖子(用于说明一对多关系)

  • Users & Profiles (for illustrating One to One relationships)
  • Users & Posts (for illustrating One to Many relationships)

// ONE TO ONE relationship (with Users already created)
$factory->define(App\Profile::class, function (Faker\Generator $faker) {
    return [
        'user_id' => $faker->unique()->numberBetween(1, App\User::count()),
        // Rest of attributes...
    ];
});

// ONE TO MANY relationship (with Users already created)
$factory->define(App\Posts::class, function (Faker\Generator $faker) {
    $users = App\User::pluck('id')->toArray();
    return [
        'user_id' => $faker->randomElement($users),
        // Rest of attributes...
    ];
});

这篇关于使用模型工厂一对一和&定义Laravel外键.一对多关系而无需创建不必要的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆