Hmm...there is an updateOrCreate method.
/**
* Create or update a related record matching the attributes, and fill it with values.
*
* @param array $attributes
* @param array $values
* @return \Illuminate\Database\Eloquent\Model
*/
public function updateOrCreate(array $attributes, array $values = [])
{
$instance = $this->firstOrNew($attributes);
$instance->fill($values);
$instance->save();
return $instance;
}
I believe for this method, the first argument is for any matching attributes. The second argument is for the new values so you might able to do something like this.
$order->location()->updateOrCreate([], $arrayOfData);
Thanks for the info @thomastkim. I couldn't get that to work, my model is using a hasOne relationship which returns a HasOne class object, which is en extention of the base Relation class, which doesnt have the updateOrCreate method. Infact I couldnt find that method you posted anywhere in the laravel source. I am working with 4.2.
I was able to get close to what I am looking for by grabbing the related model directly,
// This will create the new row successfully
$order->location()->getRelated()->updateOrCreate(['data']);
// However the order still isn't aware of the new related row
var_dump($order->location);
// This outputs NULL even though the related row was created
// The only way to get the newly added location is to go
$location = $order->find(1)->location;
// This is an unnecessary database call
I was able to figure it out by looking at the laravel 5 source code and the function you provided @thomastkim! Thanks!
For anyone interested,
$order->setRelation(
'location',
$order->location()
->getRelated()
->updateOrCreate(['data'], ['data'])
);
That is weird. HasOne extends HasOneOrMany, which does have the function.
But glad you got it to work! :)
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community