I have a rather complex structure that contains multiple relations. If my relations are defined this way, how can I load all of them in one call?
Model
(has many) ChildModels1
Child1a
Child1b
...
(has many) ChildModels2
Child2a
Child2b
...
(has many) ChildModels3
Child3a
Child3a
Child3aa
Child3ab
...
I'm able to do the following:
$entity = Entity::find($id)->load('ChildModels1', 'ChildModels2', 'ChildModels3');
But I'm not sure how to load all the child relations too.
This can be achieved with Eager Loading:
Entity::where('id', $id)->with('relation1.subrelation1', 'relation1.subrelation2', 'relation2.subrelation1', 'relation2.subrelation2')->get();
When accessing Eloquent relationships as properties, the relationship
data is "lazy loaded". This means the relationship data is not
actually loaded until you first access the property. However, Eloquent
can "eager load" relationships at the time you query the parent model.
Eager loading alleviates the N + 1 query problem.
You can read more about this in the Laravel documentation on eager loading.
Related
In Laravel it is possible to use the hasMany() and belongsTo() methods in the Model to specify the relation between tables. This for one-to-many relations.
However in the migration files, this relation is also specified for the database by the
$table->foreign('userId')->references('id')->on('users')
Why does it to be specified double in Laravel?
Why does Laravel doesn't fetch the relationship from the database, and do we have to specify it double?
Laravel offers hasMany() and belongsTo() etc for quicker access to parent/child records between tables on the model level. For instance, you may access the child record with ->{attr}, which makes the child record as if an attribute of the parent record.
It also comes with other benefits, such as eager loading of child record by providing the relationship parameter into ->with() function.
In comparison, the usage of relation in migration files are to enforce relationship between tables on database level.
I'm working on a legacy Zend 1 project that's in the process of migrating to Laravel via the Strangler Pattern, and I'm using Eloquent for some of the database queries (though not all as they're still in the process of being migrated). Because Zend 1 can't work on any version of PHP higher than 7.1, it's stuck on the version of Eloquent from Laravel 5.8 until further notice.
I have one particular table containing navigation items, which has a nullable polymorphic relation for content items that uses a morph map to map the Eloquent models to the item types. One type, static doesn't have an Eloquent model assigned to it since it's just a container for other navigation items. Trying to eager load the relation on any items with the static type breaks it because it's not defined in the morph map, and setting it to null doesn't resolve the issue either.
Right now I load the items with a link type of static in a separate query and merge them with the query that gets the remaining navigation items, but this means there are two separate queries and that's not great for performance. Using a union doesn't resolve the issue because the eager load is a separate query from the one for the navigation items.
I know that it's possible to call load() on a collection after it's already been retrieved via a query in order to eager load a relation, and that it's also possible to constrain the eager load so that, for instance, a WHERE clause can be applied when loading the relation. What I'm trying to find is a means to ensure that the query only attempts to eager load the relation if the item type is not static. In other words, constraining not the query to get the relation, but excluding that record from the query so no attempt is made to retrieve the non-existent relation for that record.
Does anyone know if this is possible? One solution I can think of is to split off the items that aren't static in collections and apply load() there, but that's rather cumbersome and I was hoping there was a more elegant method.
I have two models, Box and BoxLocations. Box has a hasMany relation to BoxLocations and BoxLocations has a belongsTo relationship to Box.
BoxLocations also has an attribute that is appended to the model that required a single piece of information from the Box relation.
I have noticed that when calling Box::with(['BoxLocations']->)all(); I see that the BoxLocations model is re-loading the Box relationship. This is happening for each BoxLocation (50 odd times)
Does laravel not track that the Box was already loaded from the initial Box::with(['BoxLocations']->)all(); request and then pass this to the BelongsTo relationship?
I am trying to optimise a web system and when the taken attribute is loaded (annoyingly its required every time its loaded as well) its causing 50 odd hits to the database for the same Box model it has already loaded.
If laravel does not do this - is there a better way in which to achieve the above?
Laravel uses eager loading when you use the with() method.
When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem.
So if you do this:
$boxes = Box::with('BoxLocations')->get();
It will load the relations already, but lets' say you do this:
$boxes = Box::all();
foreach($boxes as $box)
{
echo box->boxlocation->name;
}
If you have 50 Boxes, this loop would run 51 queries.
But when you use the with method and eager load the relation, this loop will run only 2 queries.
You could also use Lazy Eager Loading and decide when you want to load the relationship
Laravel Version: 5.5
PHP Version: 7+
Database Driver & Version: mysql 5.7+
Scenario:
I have a SaaS application that has flexible database structure, so its fields are bound to change, especially given it has a Json field (for any extra database structure to be created from client side of the application), including relationship based fields. so Account Table can have dynamically created employee_id field, and thus the need to access relationships dynamically
Problem:
I need to EagerLoad models based on this dynamic relationship. If I had something like this:
// Account Model
public function employee(){
return $this->belongsTo(App\Employee);
}
it would be easy. But what I have is this:
public function modelBelongsTo(){
return $this->belongsTo($dynamicClassName, $dynamicForeignKey);
}
Now if I eager load this, I'll get Account Model instance with related Employee on key modelBelongsTo. This is how Eloquent Names based on the function of eagerload. But after this I cannot use this function again to eagerload a second model because it'll just overwrite results on modelBelongsTo key.
Possible Solution Directions:
1) Can I Somehow change laravel's process to use a name I provide?
or
2) Can I write functions on the fly to overcome this so I'll write employee function on the fly?
or
3) Worst Case Scenario: I iterate over all records to rename their keys individually because I am using a pagination, it wouldn't that big of a deal to loop over 10 records.
Us a morph relationship
define the various dynamic classnames say
Employee
Boss
Morph works by having the related key and the table name stored in the parent table, it means to relate them you have to use a join or an orm and you cant have foreign key constraint on it as it links to different tables.
then have your account have morphs where
we have
Account
as top class
then we have
EmployeeAccount, BossAccount
which have their relation to boss and employee
then in Account have morphto relation call it specificAccount()
to which in its child morphs have the morph relation to Account
then add it to $with so to eager load them so when fetching account you could simply do
$account ->specificAccount
to get its morph child. which is nullable
This is totally dynamic such that if you have other classes in future you can just add and add the morph relationship. This may be applied to any reflection or runtime evaluated and loaded classes/code though it is not advisable to do this, as you can always edit code to create new functionality without affecting previous.
I have two tables: assets and asset_classifications. The tables have one-to-many relationship, where an asset has one asset classification, and asset_classifications have many assets.
I'm trying to run a query to get all assets which has an asset_classification name of "laptops", for example. I'm trying to do this by running this eager load with a constraint:
$laptops = Asset::with(array('classification'=>function($query){
$query->where("name","=","laptops");
}))->get();
foreach($laptops as $laptop){
echo $laptop->serial_number."<br/>";
}
name is a column from asset_classifications table. I already formed the one-to-many relationship by setting up the needed methods for my Asset and AssetClassification models.
The problem with my eager load is that it gets all the assets, seeming to ignore my eager loading constraint which tries to get only the "laptops". I think the problem is in my code or my understanding of eager loading, but I don't know which. I'm still new to this and I hope someone can help me.
with is used to filter related models, while you need whereHas for filtering main queried model by related table constraints:
$laptops = Asset::whereHas('classification', function ($query) {
$query->where("name","=","laptops");
})->get();