Ben Swinburne
Ben Swinburne

Reputation: 26467

Manually inject model relation using Eloquent

How can I add a model into the relations array of another model?

E.g.

I want to add $domain to $owner->relations[] so that I can just use $owner->domain later on in my code.

The reason for doing this is such that in one particular controller i only need a partial data set from each model so use fluent to query with a join for performance reasons then fill the models.

Then for readability's sake I'd like to use $owner->domain->id etc

$domain->owner()->associate($owner); gives me a $domain->owner option

But then I can't work out the opposite version

$owner->domain()->associate($domain)
$owner->domain()->attach($domain)

both result in the following fatal error

Call to undefined method Illuminate\Database\Query\Builder::[attach|associate] ()

NB: I don't want to save anything as I've already loaded all the data i need.

Upvotes: 32

Views: 20127

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152870

setRelation() should work. It sets the value in the relations array.

$owner->setRelation('domain', $domain);

When setting a one to many relationship, you may need to use values():

$owner->setRelation('domains', $domains->values());

Upvotes: 63

Related Questions