【问题标题】:Seed a pivot table using factories in Laravel使用 Laravel 中的工厂播种数据透视表
【发布时间】:2017-02-10 15:56:00
【问题描述】:

我是 Laravel 的新手,我正在寻找一种使用 factories 为数据透视表播种的好方法。我不想使用普通播种机。我会告诉你这个案例:

我有三个表(usersskillsuser_skill)。

users                user_skill                 skills
+----------------+   +----------------------+   +-----------------+
| id  | name     |   | user_id | section_id |   | id  | skills    |
+----------------+   +----------------------+   +-----------------+
| 1   | Alex     |   |         |            |   | 1   | draw      |
|----------------|   |----------------------|   |-----------------|
| 2   | Lucy     |   |         |            |   | 2   | program   |
|----------------|   |----------------------|   |-----------------|
| 3   | Max      |   |         |            |   | 3   | social    |
|----------------|   |----------------------|   +-----------------+
| 4   | Sam      |   |         |            |
+----------------+   +----------------------+

有没有一种好方法可以将用户表的真实Id 和技能表的真实Id 用作数据透视表的种子?我想随机做,但我不想要与任何 id 不匹配的随机数。我希望 Id 与 usersskills 匹配。

我不知道如何开始,我正在寻找一个很好的例子。也许是这样的?

$factory->defineAs(App\User::class, 'userSkills', function ($faker) {
    return [
        'user_id' => ..?
        'skills_id' => ..?
    ];
});

【问题讨论】:

    标签: php laravel pivot-table factory laravel-seeding


    【解决方案1】:

    对于那些正在使用 laravel 8.x 并正在寻找此类问题的解决方案的人;

    在 laravel 8.x 中,您可以使用魔术方法来喂您的枢轴, 例如,如果您在 User 模型中有一个名为“userSkills”的 belongsToMany 关系,您应该以这种方式提供数据透视表:

    User::factory()->hasUserSkills(1, ['skills' => 'draw'])->create();

    You can find the documentation here

    【讨论】:

    • 任何想法如何为多态关系做到这一点?例如。可评论()
    【解决方案2】:

    我遇到了类似的问题,我在 Laravel 测试中以这种方式解决了。

    不需要创建新的 UserSkills 模型:

    版本 Laravel 5.7

    数据库

    users                user_skill                               skills
    +----------------+   +------------------------------------+   +-----------------+
    | id  | name     |   | user_id | section_id | state_skill |   | id  | skills    |
    +----------------+   +------------------------------------+   +-----------------+
    | 1   | Alex     |   |         |            |             |   | 1   | draw      |
    |----------------|   |----------------------|-------------|   |-----------------|
    | 2   | Lucy     |   |         |            |             |   | 2   | program   |
    |----------------|   |----------------------|-------------|   |-----------------|
    | 3   | Max      |   |         |            |             |   | 3   | social    |
    |----------------|   |----------------------|-------------|   +-----------------+
    | 4   | Sam      |   |         |            |             |
    +----------------+   +----------------------+-------------+
    

    用户.php

    <?php
    
    namespace App;
    
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Contracts\Auth\MustVerifyEmail;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    
    use Illuminate\Database\Eloquent\SoftDeletes;
    
    class User extends Authenticatable
    {
        use Notifiable;
        use SoftDeletes;
        
        public function skills()
        {
            return $this->belongsToMany('App\Skill')
                    ->withTimestamps()
                    ->withPivot('state_skill');
        }
    }
    

    DataBaseTest.php

    <?php
    
    namespace Tests\Unit;
    
    use Tests\TestCase;
    use Illuminate\Foundation\Testing\WithFaker;
    use Illuminate\Foundation\Testing\RefreshDatabase;
    use Illuminate\Support\Facades\Schema;
    
    class DataBaseTest extends TestCase
    {
    
        /**
         * @test
         */    
        public function test_create_user_skill()
        {
           // Create DataBase
           $users = factory(\App\User::class, 1)
               ->create()
               ->each(function ($user) {
    
                    // Create Models Support
                    $skill = factory(\App\Skill::class)->create();
                    
                    // Create Pivot with Parameters
                    $user->skills()->attach($skill->id,[
                        'state_skill' => 'ok'
                    ]);
     
                });
    
            // Testing
            // ...
            $this->assertTrue(true);
        }
    }
    

    【讨论】:

      【解决方案3】:

      我不认为这是最好的方法,但它对我有用。

      $factory->define(App\UserSkill::class, function (Faker\Generator $faker) {
          return [
              'user_id' => factory(App\User::class)->create()->id,
              'skill_id' => factory(App\Skill::class)->create()->id,
          ];
      });
      

      如果您不想仅为数据透视表创建模型,可以手动插入。

      DB::table('user_skill')->insert(
          [
              'user_id' => factory(App\User::class)->create()->id,
              'skill_id' => factory(App\Skill::class)->create()->id,
          ]
      );
      

      或者,使用随机的现有值。

      DB::table('user_skill')->insert(
          [
              'user_id' => User::select('id')->orderByRaw("RAND()")->first()->id,
              'skill_id' => Skill::select('id')->orderByRaw("RAND()")->first()->id,
          ]
      );
      

      【讨论】:

      • 但是这样你需要为数据透视表user_skill创建一个模型UserSkill?这没有必要吧?没有办法只使用usersskills 表中的当前id 来播种黑貂?
      猜你喜欢
      • 2021-06-11
      • 1970-01-01
      • 2019-02-13
      • 2017-09-19
      • 2015-09-16
      • 2020-08-04
      • 2018-04-04
      • 1970-01-01
      • 2017-08-02
      相关资源
      最近更新 更多