Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent/Laravel: is there a counterpart to object->load('relation'), eg. object->unload('relation')?

When i update a relation, e.g. update parent_id on Child (Child belongsTo Parent, Parent hasMany Child) and respond with the Child->Parent object, somehow the returned Parent is still the old one. I think this is because the Parent is already loaded at that time.

I now want to unlaod the relations so the new Parent is fetched from db again.

Is there a way to unload the loaded relationships? Like you can lazy-load by using model->load('relation'), can you also unload it again?

Thanks a lot!

like image 516
jsphpl Avatar asked Nov 04 '14 09:11

jsphpl


People also ask

Does Laravel have relation?

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

What is relation 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 lazy loading & eager loading in Laravel?

} Dynamic properties are "lazy loading", meaning they will only load their relationship data when you actually access them. Because of this, developers often use eager loading to pre-load relationships they know will be accessed after loading the model.


1 Answers

Unloading relations can be done by passing an empty array to the model

$child->setRelations([]);

when you call a relation on the model after that, it will be reloaded at that moment.

.. in the current version (5.x) at least, maybe not at the time of your question :)

like image 195
CommonToast Avatar answered Sep 20 '22 12:09

CommonToast