Manually inject model relationship with Eloquent
How can I add a model to the relationship array of another model?
eg.
- Domain belongs to the Owner.
- Owner of hasOne Domain.
- I have $ domain (domain instance).
- I have an owner (owner instance).
I want to add $domain
in $owner->relations[]
so that I can just use $owner->domain
later in my code.
The reason for this is that in one particular controller, I only need a partial dataset from each model, so use freely query for a connection to improve performance and then populate the models.
Then, for readability, I would like to use $owner->domain->id
etc.
$domain->owner()->associate($owner);
gives me the option $domain->owner
But then I cannot work out the opposite version
$owner->domain()->associate($domain) $owner->domain()->attach($domain)
both result in the following fatal error
Calling undefined method Illuminate \ Database \ Query \ Builder :: [attach | associate] ()
NB: I don't want to save anything as I have already loaded all the data I need.
source to share