所以我有一个项目表:
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));
user
和project
在其班级中具有相同的小时数关系:
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function hours(): HasMany
{
return $this->hasMany(Hour::class);
}
如果可能,我将如何去做呢?
答案 0 :(得分:0)
我认为处理此问题的最佳方法是将Hours
的保存分离为模型的独立实例,然后像这样将两者同步:
$hour = Hour::create($hours);
$project->hours()->syncWithoutDetaching([$hour->id]);
$user->hours()->syncWithoutDetaching([$hour->id]);