Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually inject model relation using Eloquent

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

E.g.

  • Domain belongsTo Owner.
  • Owner hasOne Domain.
  • I have $domain (instance of Domain).
  • I have $owner (instance of Owner).

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.

like image 910
Ben Swinburne Avatar asked Jul 08 '15 09:07

Ben Swinburne


People also ask

How do you add a relationship in Laravel?

To define a relationship, we need first to define the post() method in User model. In the post() method, we need to implement the hasOne() method that returns the result. Let's understand the one to one relationship through an example. First, we add the new column (user_id) in an existing table named as posts.

What is with () in Laravel?

with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.

What is BelongsTo in Laravel?

BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.


1 Answers

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

$owner->setRelation('domain', $domain); 
like image 147
lukasgeiter Avatar answered Oct 22 '22 18:10

lukasgeiter