doucao1888 2016-10-02 16:33
浏览 57
已采纳

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

I'm new to Laravel and I'm looking for a good way to seed a pivot table using factories. I don't want to use plain seeders. I'll show you the case:

I have three tables (users, skills, and 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      |   |         |            |
+----------------+   +----------------------+

Is there a good way to take real Id's of the Users table and real Id's of Skills table to seed the pivot table? I want to do it randomly, but I don't want random numbers that doesn't match to any id. I want the Id to match with the users and skills.

I don't know how to start, and I'm looking for a good example. Maybe something like this?

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

2条回答 默认 最新

  • douzhuan4406 2016-10-02 16:55
    关注

    I do not think that this is the best approach but it works for me.

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

    If you do not want to create a model just for the pivot table, you can insert it manually.

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

    Or, with random existing values.

    DB::table('user_skill')->insert(
        [
            'user_id' => User::select('id')->orderByRaw("RAND()")->first()->id,
            'skill_id' => Skill::select('id')->orderByRaw("RAND()")->first()->id,
        ]
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题