一次调用即可创建具有多个关系的项目

时间:2018-10-02 16:07:10

标签: laravel laravel-5.7

所以我有一个项目表:

Schema::create('projects', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id');
    $table->string('name');
    $table->string('reference')->nullable();
    $table->date('started')->nullable();
    $table->date('ended')->nullable();
    $table->string('industry')->nullable();
    $table->string('operatives')->nullable();
    $table->timestamps();
    $table->softDeletes();
});

我有一个小时表:

Schema::create('hours', function (Blueprint $table) {
    $table->increments('id');
    $table->string('hours');
    $table->date('date')->nullable();
    $table->text('notes')->nullable();
    $table->integer('project_id');
    $table->integer('user_id');
    $table->softDeletes();
    $table->timestamps();
});

现在,是否可以在一个调用中同时创建与project_id和user_id的关联?

我知道我可以执行以下操作(将user_id添加到工时):

$hours = [
    'hours'      => $request->hours,
    'date'       => $request->date,
    'operatives' => $request->operatives,
    'notes'      => $request->notes,
    'user_id'    => auth()->user()->id,
];

$create = $project->hours()->save(new $this->hour($hours));

但是我正在尝试做类似的事情:

$hours = [
    'hours'      => $request->hours,
    'date'       => $request->date,
    'operatives' => $request->operatives,
    'notes'      => $request->notes,
];

$create = $project->hours()->save(auth()->user()->save($hours));

userproject在其班级中具有相同的小时数关系:

/**
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function hours(): HasMany
{
    return $this->hasMany(Hour::class);
}

如果可能,我将如何去做呢?

1 个答案:

答案 0 :(得分:0)

我认为处理此问题的最佳方法是将Hours的保存分离为模型的独立实例,然后像这样将两者同步:

$hour = Hour::create($hours);
$project->hours()->syncWithoutDetaching([$hour->id]);
$user->hours()->syncWithoutDetaching([$hour->id]);