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.
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.
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.
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.
setRelation()
should work. It just sets the value in the relations
array.
$owner->setRelation('domain', $domain);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With