我有一个餐厅应用程序,我为我的餐厅(用户)和菜肴类型(类型)创建了播种机。 由于这两个表具有多对多的关系,因此我有一个名为 type_user 的数据透视表。
但是当我运行播种机时,这张桌子不会播种。 如何使用用户表和类型表中的 id 在 UserSeeder 中为数据透视表 type_user 播种?
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\User;
use App\Type;
class UsersSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$users = config('restaurants');
foreach ($users as $user) {
$new = new User();
$new->name = $user['name'];
$new->slug = Str::slug($user['name'], '-');
$new->email = $user['email'];
$new->password = Hash::make($user['password']);
$new->address = $user['address'];
$new->vat_number = $user['vat_number'];
$new->types()->attach($user->id);
if (array_key_exists('thumb', $user)) {
$new->thumb = $user['thumb'];
} else {
$new->thumb = 'users_thumbs/food_placeholder.jpg';
}
$new->save();
}
}
保存后尝试附加,您需要有要附加的
type_id
user
$user = $new->save();
$user->type()->attach($type_id)
还要确保您已在模型中设置关系。
我习惯于调用
has
方法(User::factory()->has()
)它允许您在没有任何数据的情况下生成,但您应该为模型创建工厂。例如:
迁移:
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('role');
$table->timestamps();
});
Schema::create('role_user', function (Blueprint $table) {
$table->id();
$table->foreignIdFor(\App\Models\User::class);
$table->foreignIdFor(\App\Models\Role::class);
$table->timestamps();
});
用户型号:
class User extends Authenticatable
{
use HasFactory;
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
播种机:
class DatabaseSeeder extends Seeder
{
public function run(): void
{
User::factory(10)
//->for(Profile::factory(), 'profile')
->has(Role::factory(2), 'roles');
}
}
has
许多关系的方法。 for
单一关系方法。但它用于 laravel 最新版本