我有一个组的列表,每个组都有一个属性列表,如下所示

//sets
Schema::create('sets', function (Blueprint $table) {
    $table->id();
    $table->string('name');
});

//groups
Schema::create('groups', function (Blueprint $table) {
    $table->id();         
    $table->string('name');
    $table->foreignId('set_id')->constrained('sets')->onDelete('cascade');
});

//attributes
Schema::create('attributes', function (Blueprint $table) {
    $table->id();         
    $table->string('name');
});

//set_group_attributes
Schema::create('set_group_attributes', function (Blueprint $table) {
    $table->foreignId('set_id')->constrained('sets')->onDelete('cascade');
    $table->foreignId('group_id')->constrained('groups')->onDelete('cascade');
    $table->foreignId('attribute_id')->constrained('attributes')->onDelete('cascade');
    $table->integer('position');
    $table->unique(['set_id', 'attribute_id']);
});

我需要保存包含组和属性的集合,这是我的代码:

$set = Set::create(['name' => $request->name]); ---> save the set
$set->groups()->createMany($request->groups); ---> save the group

//set model
public function groups(): HasMany
{
  return $this->hasMany(Group::class, 'set_id','id');
}

我的问题是,如何用LARLAVELEloquent 保存属性?

推荐答案

在这里,我们可以使用Attach Like in Docs with UndersToMany

//group model
/**
 * @return BelongsToMany
 */
public function attributes(): BelongsToMany
{
    return $this->belongsToMany(Attribute::class, 'set_group_attributes', 'group_id', 'attribute_id')->withPivot('position');
}

// save attributes of groups
foreach ($attributes as $attribute) {
    $group->attributes()->attach($attribute['id'], ['set_id' => $model->id, 'position' => $attribute['position']]);
}

Laravel相关问答推荐

如何在 Laravel 中获取特定月份的最后一个日期?

Laravel 获取具有多对多关系的中间表数据

Laravel Eloquent:组合列(或自定义属性)上的 Where 子句

将数据从控制器传递到 Laravel 中的视图

Laravel 连接表

插入重复键时,laravel eloquent 忽略错误

如果用户在 Laravel 中经过身份验证,如何签入 Vue 组件?

没有 index.php 的路由不起作用

如何使用 Laravel 模型访问数据库视图?

Laravel 5.5 在迁移文件中设置整数字段的大小

调用未定义的方法 Maatwebsite\Excel\Excel::load()

如果值存在于另一个字段数组中,Laravel 验证规则

Laravel:自定义或扩展通知 - 数据库模型

Laravel assets资源与混合

Laravel Eloquent模型如何从关系表中获取数据

在 Laravel 5.4 中将文件存储在公共目录和存储中的区别

控制器中的laravel foreach循环

Carbon解析到 ISO8601

如何判断是否连接到 Laravel 4 中的数据库?

count() 参数必须是数组或在 laravel 中实现可数的对象