database queries, otherwise your memory footprint will be significant, and growing as your database increases in size
What loads faster - eloquent query or collection search?
The question is rather rhetorical. But I will definitely meet him soon. Therefore, I want to ask for advice in advance. Example: There is a table of products and they have many-to-many relationships by category, color, brand, etc. I need to get all the products from the Clothing & Sneakers category and also filter the ones that are blue or red, brand adidas.
Option 1:
Get all products from the specified categories, and then filter the data from the resulting collection.
Get all products from the specified categories.
$allProducts = Product::whereHas('categories', function ($query) use ($idsChildCategories){
$query->whereIn('categories.id', $idsChildCategories);
})
->with('categories', 'genders', 'brands', 'colors', 'materials', 'seasons', 'countries', 'features', 'ages')
->get();
After this collection, filter out those products that have the color blue or red, the adidas brand.
$products = $allProducts->
//Here is some code that filters the resulting collection by color and brand (so far I have not completed this task)
->paginate('100');
Option 2: Make two queries to the database.
- Get all products from the specified categories.
$allProducts = Product::whereHas('categories', function ($query) use ($idsChildCategories){
$query->whereIn('categories.id', $idsChildCategories);
})
->with('categories', 'genders', 'brands', 'colors', 'materials', 'seasons', 'countries', 'features', 'ages')
->get();
- Get all products from the specified categories that have the color blue or red, brand adidas.
$products = Product::whereHas('categories', function ($query) use ($idsChildCategories){
$query->whereIn('categories.id', $idsChildCategories);
})
->whereHas('brands', function($q) {
$q->whereIn('id', ['1','2']);
})
->whereHas('brands', function($q) {
$q->whereIn('id', ['1']);
})
->with('categories', 'genders', 'brands', 'colors', 'materials', 'seasons', 'countries', 'features', 'ages')
->get();
Looking ahead, I will explain why I need 2 requests. To display in the catalog, I get a list of products. But in order to specify all possible attributes that will expand this list of products, I make a request for a category without filtering by attributes. After I receive all possible attributes.
Which of these will work faster if there are a million products in the catalog?
Please or to participate in this conversation.