使用Laravel中的工厂为枢轴表播种

时间:2016-10-02 16:33:49

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

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

我有三个表(用户技能 user_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与用户技能匹配。

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

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

3 个答案:

答案 0 :(得分:6)

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

$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,
    ]
);

答案 1 :(得分: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      |   |         |            |             |
+----------------+   +----------------------+-------------+

User.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);
    }
}

答案 2 :(得分:1)

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

在laravel 8.x中,您可以使用魔术方法喂食您的枢轴, 例如,如果在用户模型中有一个名为“ userSkills”的belongsToMany关系,则应通过以下方式喂入数据透视表:

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

You can find the documentation here