0

So I have a project table:

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

And I have an hours table:

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

Now, is there anyway to create an association with both the project_id and user_id in one call?

I know I can do the following (adding the user_id to the hours):

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

But I am trying to do something like so:

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

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

Both user and project have the same hours relation in their classes:

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

Is this possible, if so, how would I go about doing it?

  • are there any other fields in the hours table? – zjbarg Oct 02 '18 at 16:13
  • @barghouthi updated with full table structure –  Oct 02 '18 at 16:14
  • I see that you are trying to make it look neat. I can't find a way. If I were you I'd use Hour::create([..... 'project_id' => $project->id, 'user_id' => $user->id]. at least it is consistent – zjbarg Oct 02 '18 at 16:40

1 Answers1

0

I think the best way to handle this would be to separate the saving of Hours as an independent instance of the model and then sync it with both like so:

$hour = Hour::create($hours);
$project->hours()->syncWithoutDetaching([$hour->id]);
$user->hours()->syncWithoutDetaching([$hour->id]);
Jaime Rojas
  • 549
  • 2
  • 6
  • Not possible, because hours requires both a project_id and user_id –  Oct 02 '18 at 16:22
  • You're right. If that's the case, what you're currently doing (passing the `user_id` within the parameters) is the way to go. Something like this `$create = $project->hours()->save(auth()->user()->save($hours));` will not work because the `save->()` method returns `true / false` based on wether or not it was possible to save. It won't allow you to work it the way you want it. – Jaime Rojas Oct 02 '18 at 16:28