0

所以我有一个项目表:

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);
}

这可能吗,如果可以,我将如何去做?

4

1 回答 1

0

我认为处理此问题的最佳方法是将保存Hours作为模型的独立实例分开,然后将其与两者同步,如下所示:

$hour = Hour::create($hours);
$project->hours()->syncWithoutDetaching([$hour->id]);
$user->hours()->syncWithoutDetaching([$hour->id]);
于 2018-10-02T16:20:10.170 回答