Skip to content

Commit

Permalink
Use the relation query instance to perform updateOrCreate (#17105)
Browse files Browse the repository at this point in the history
  • Loading branch information
themsaid authored and taylorotwell committed Jan 4, 2017
1 parent f637c2f commit 865bdd3
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,39 @@ public function findOrFail($id, $columns = ['*'])
throw (new ModelNotFoundException)->setModel(get_class($this->parent));
}

/**
* Get the first related model record matching the attributes or instantiate it.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model
*/
public function firstOrNew(array $attributes)
{
if (is_null($instance = $this->where($attributes)->first())) {
$instance = $this->related->newInstance($attributes);
}

return $instance;
}

/**
* Create or update a related record matching the attributes, and fill it with values.
*
* @param array $attributes
* @param array $values
* @param array $joining
* @param bool $touch
* @return \Illuminate\Database\Eloquent\Model
*/
public function updateOrCreate(array $attributes, array $values = [])
{
$instance = $this->firstOrNew($attributes);

$instance->fill($values)->save();

return $instance;
}

/**
* Execute the query as a "select" statement.
*
Expand Down

0 comments on commit 865bdd3

Please sign in to comment.