Laravel - 播种多对多关系 [英] Laravel - Seeding Many-to-Many Relationship

查看:27
本文介绍了Laravel - 播种多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 users 表和一个 roles 表,其中有一个多对-许多 关系.这两个表连接到一个名为 role_user 的联结表.

I have a users table and a roles table that has a many-to-many relationship. These two tables are connected to a junction table called role_user.

这是表及其连接的模型.

以下是我的 Laravel 项目中的模型:

Below are the Models in my Laravel project:

用户

namespace App;

use IlluminateDatabaseEloquentModel;

class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany('AppRole');
    }
}

角色

namespace App;

use IlluminateDatabaseEloquentModel;

class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany('AppUser');
    }
}

以下是 Laravel 项目中的工厂文件:

Below is the Factory file in the Laravel project:

$factory->define(AppUser::class, function (FakerGenerator $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
    ];
});

$factory->define(AppRole::class, function (FakerGenerator $faker) {
    return [
        'role' => $faker->realText($maxNbChars = 2),
        'description' => $faker->realText($maxNbChars = 20),
    ];
});

以下是 Laravel 项目中的种子文件:

Below is the Seed file in the Laravel project:

public function run()
{
    factory(AppUser::class, 50)->create()->each(function ($u) {
        $u->roles()->save(factory(AppRole::class)->make());
    });

    factory(AppRole::class, 20)->create()->each(function ($u) {
        $u->users()->save(factory(AppUser::class)->make());
    });
}

这应该填充 users 表和 roles 表,但是我如何去填充 <强>role_user 表?(我没有连接表的模型文件.)

This should populate the users table and the roles table but how do I go about populating the role_user table? (I don't have a Model file for the junction table.)

我对此很陌生,因此将不胜感激.谢谢.

I'm very new at this so any help would be appreciated. Thanks.

推荐答案

您可以使用 attach()sync() 方法 用于多对多关系.

You can use attach() or sync() method on a many-to-many relationship.

有多种方法可以解决这个问题.这是其中之一:

There are multiple ways you can approach this. Here one of them:

// Populate roles
factory(AppRole::class, 20)->create();

// Populate users
factory(AppUser::class, 50)->create();

// Get all the roles attaching up to 3 random roles to each user
$roles = AppRole::all();

// Populate the pivot table
AppUser::all()->each(function ($user) use ($roles) { 
    $user->roles()->attach(
        $roles->random(rand(1, 3))->pluck('id')->toArray()
    ); 
});

这篇关于Laravel - 播种多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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