How to order by eager loaded relationship in Laravel 5.5? - laravel

The code below works perfectly and displays all products with discounts in JSON Format for my API. But I want the result ordered by id in the discounts table. Something like orderBy('discount.id', 'desc'). Can anyone provide a solution for this? How it is possible to use orderBy with id column in discount table using has()?
public function promotions()
{
return $this->prepareResult(true, Product::has('discount')->where([
'company_id' => 1, 'is_active' => 1
])->with('category')->with('discount')->get(), [], "All Promotions");
}

You can use a function within your with statement:
public function promotions()
{
return $this->prepareResult(true, Product::has('discount')
->where(['company_id'=> 1, 'is_active'=>1])
->with('category')
->with(['discount' => function ($query) {
return $query->orderBy('id','DESC');
}])->get(), [],"All Promotions");
}
You can read about this here in the documentation.

If you want to go the collection method route instead of Alex's answer (which is also valid), you can just continue to chain collection methods after get. Since you included the with(), you can do
->get()->sortBy('discount.id')
https://laravel.com/docs/5.6/collections#method-sortby
Not related to your question, but wanted to point out that you can pass multiple arguments to with() so that you don't call it twice.
Product::has('discount')->where(['company_id'=> 1, 'is_active'=>1])->with('discount', 'category')->get()

As DevK mentioned, you need to do a join and then you can sort your products by that. The trick here is that you join the discounts table to your products table, but only select the id column (named as discount_id) from your discounts table so you can sort by those records.
In the below example, I assumed that your
Category model's table is categories
Product model's table is products
Discount model's table is discounts
products table references a discount.id as discount_id
This code will return every column from the products table plus a discount_id column, which you can ignore, it's only there for the sorting. It will also keep it as a collection with the relationships that you stated above.
public function promotions()
{
return $this->prepareResult(
true,
Product::has('discount')
->where(['company_id' => 1, 'is_active' => 1])
->with('category')
->with('discount')
->selectRaw('products.*, discounts.id as discount_id')
->join('discount', 'products.discount_id', '=', 'discounts.id')
->orderBy('discount_id', 'DESC')
->get(),
[],
"All Promotions"
);
}

Related

Laravel Eloquent with() selecting specific column doesn't return results

Say I have 2 models, Category and POI where 1 Category can have many POIs.
$categoryDetails = Category::with([
'pois' => function ($query) {
$query->where('is_poi_enabled', true);
},
])->findOrFail($id);
The above query returns results from the specific Category as well as its POIs.
However, with the query below:
$query->select('id', 'name')->where('is_poi_enabled', true);
The POIs become empty in the collection.
Any idea why this is happening? When added a select clause to the Eloquent ORM?
While doing a select it's required to fetch the Relationship local or Primary key.
For an example POIs table contains category_id then it's required to select it
Try this:
$categoryDetails = Category::with([
'pois' => function ($query) {
$query->select(['id', 'category_id', 'is_poi_enabled'])
->where('is_poi_enabled', true);
},
])->findOrFail($id);
Good luck!

Eloquent select with() based on foreign key

I have a table with user data (users) and a table with prices (prices).
My prices table can contain multiple prices pr. user since I want to keep historical data.
I've defined my relation as a one-to-one
$this->hasOne("App\Model\Price","userid","id")->orderBy("id","desc")->take(1);
to allow me to see the users current price.
What I want to do now, is to select every user that has a current price of 100, but how do I do this? I know I could go for a left join, but as I read the documentation, it should be possible without a left join.
I've built a pseudo-query to explain what I'm after;
User::with("price")->where("prices.price","100")->get();
I've read through the documentation (Eloquent: Querying relationships), but that doesn't seem to be useful to my question.
I've also read several questions here on SO but unfortunately to no avail.
You may try this:
$currentPrice = 100;
$users = User::whereHas('price', function($query) use ($currentPrice) {
$query->where('price', $currentPrice); // price is the field name
})
->with("price")->get();
Since you have more than a single price for per user then you may also declare another relationship method to get all the price models instead of one and you may do it using something like this:
// In User model
public function prices()
{
return $this->hasMany("App\Model\Price", "userid", "id");
}
In this case, with::price will give you the last single record and with::prices will give you all the related prices. So, if you want then you may write something like the following to get all users with their all related prices who has the (latest/current) price of 100:
$currentPrice = 100;
$users = User::whereHas('price', function($query) use($currentPrice) {
$query->where('price', $currentPrice); // price is the field name
})
->with("prices") // with all prices
->get();
You can use the combination of whereHas() and with() as:
$users = User::whereHas("price", function($q) use ($currentPrice) {
$q->where("price", $currentPrice);
})
->with(["price" => function ($q) {
$query->where("price", $currentPrice);
})
->get();

Laravel 5.0 how to order an eloquent with() query

I have two models: item and faq. The are in a belongsToMany with each other with a correctly created join table: item_faq (singular of both). My join table has an additional field on it for order.
In my view I get all the faq's and if they have a pivot table record I output "checked" on a checkbox. I also have drag and drop ordering on the checkbox list and that works well.
A few code notes:
// ITEMS MODEL
public function faqs(){
return $this->belongsToMany('App\Faq');
}
// FAQ MODEL
public function items(){
return $this->belongsToMany('App\Item');
}
public function hasItem($item) {
$items = $this->items->lists('id');
return in_array($item, $items);
}
Schema of join table:
item_id
faq_id
order
timestamps
My issue is that they faq's don't load sorted by the order column on the pivot table.
I am using a very simple:
$faqs = \App\Faq::with('items')->get();
To retrieve the FAQ's and this works at getting all the faq's and if they are related, it checks the checkbox.
How can I order these by the order column on the join table?
Have a look at Eager Load Constraints and I think it will help provide a solution. From the docs:
Of course, eager loading Closures aren't limited to "constraints". You may also apply orders:
$users = User::with(['posts' => function($query) {
$query->orderBy('created_at', 'desc');
}])->get();

Laravel ORM Detail -> Master History

I want to orderby orderMaster.date 'desc', but it no luck, even I added the function ($query) { $query->orderBy('date', 'desc'); } inside the "with", but it can show correctly.
OrderDetail::with('orderMaster', 'item')->get(),
The relations of the these tables
orderMaster ->(one to many) orderDetail ->(one to one) Item
I want to show the items purchase histories order by orderMaster.date desc in current order.
Thanks a lot
In your orderMaster relation you could simply do something like this:
$this->hasMany('SomeClass')->orderBy('date', 'desc');

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

I've found the concept and meaning behind these methods to be a little confusing, is it possible for somebody to explain to me what the difference between has and with is, in the context of an example (if possible)?
With
with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.
Example:
User > hasMany > Post
$users = User::with('posts')->get();
foreach($users as $user){
$users->posts; // posts is already loaded and no additional DB query is run
}
Has
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.
Example:
User > hasMany > Post
$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection
WhereHas
whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.
Example:
User > hasMany > Post
$users = User::whereHas('posts', function($q){
$q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned
The documentation has already explained the usage, so I will use SQL to explain the methods.
Example:
Assuming there is an Order (orders) has many OrderItem (order_items) and you already built the relationship between them:
// App\Models\Order:
public function orderItems() {
return $this->hasMany('App\Models\OrderItem', 'order_id', 'id');
}
These three methods are all based on a relationship.
with
Result: with() return the model object and its related results.
Advantage: It is eager-loading which can prevent the N+1 problem.
When you are using the following Eloquent Builder:
Order::with('orderItems')->get();
Laravel change this code to only two SQL:
// get all orders:
SELECT * FROM orders;
// get the order_items based on the orders' id above
SELECT * FROM order_items WHERE order_items.order_id IN (1,2,3,4...);
And then Laravel merges the results of the second SQL query with the results of the first SQL by foreign key, finally returning the collection results.
So if you selected columns without the foreign_key in a closure, the relationship result will be empty:
Order::with(['orderItems' => function($query) {
// $query->sum('quantity');
$query->select('quantity'); // without `order_id`
}
])->get();
#=> result:
[{ id: 1,
code: '00001',
orderItems: [], // <== is empty
},{
id: 2,
code: '00002',
orderItems: [], // <== is empty
}...
}]
has
Has will return the model's object when its relationship is not empty.
Order::has('orderItems')->get();
Laravel changes this code to one SQL query:
select * from `orders` where exists (
select * from `order_items` where `orders`.`id` = `order_items`.`order_id`
)
whereHas
The methods whereHas and orWhereHas put where conditions on your has queries. These methods allow you to add customized constraints to a relationship constraint.
Order::whereHas('orderItems', function($query) {
$query->where('status', 1);
})->get();
Laravel changes this code to one SQL query:
select * from `orders` where exists (
select *
from `order_items`
where `orders`.`id` = `order_items`.`order_id` and `status` = 1
)

Resources