Simple question - how do I order by 'id' in this, is'nt work
$servico = Servico::with([
'example1',
'etapas' => function ($query) {
$query->orderBy('id', 'asc');
},
'example2'])
->first();
I trying order by id or other data, but don't work.
Related
here I'd like to find the solution to simplify my query to get data using eloquent in Laravel.
$room_id = Booking::whereBetween('from', [$request->from, $request->to])
->orWhereBetween('to', [$request->from, $request->to])
->where('from', '<=', $request->from, )
->where('to', '>=', $request->from)
->pluck('room_id');
$rooms = Room::whereNotIn('id', $room_id )->get();
So here I have 2 Eloquent operations to get Rooms which not included in the Booking Table with specified requirements. So far I have no problem with it, but can you guys give me best practice to simplify from what I do? Thank you.
Make sure that 'bookings' relation is written on your Room model.
$rooms = Room::whereDoesntHave('bookings', use($request) function($q){
$q->whereBetween('from', [$request->from, $request->to])
$q->orWhereBetween('to', [$request->from, $request->to])
$q->where('from', '<=', $request->from, )
$q->where('to', '>=', $request->from)
})->get();
Your can refer laravel relationship to add it in model and after that using whereHas to query join table:
https://laravel.com/docs/9.x/eloquent-relationships
Example:
With options
protected $with = [
'product_savour'
];
Relationship
public function product_savour()
{
return $this->hasMany(ProductSavour::class, 'product_id');
}
Query
$productQuery->whereHas('product_savour', function ($query) use ($filters) {
$query->whereHas('savour', function ($query) use ($filters) {
$query->whereHas('type', function ($query) use ($filters) {
$query->whereIn('id', $filters['savour']);
});
});
});
I am new to laravel and i am trying to write a query whereby the selected stock->OrderProduct->product_id is passed to get the relevant result. The query looks like this :
$stock = Stock::where('orderProductid.product_id', $pharmacyEvent->prescription->product_id)
->whereHas('orderProduct.product.prices')
->with(['orderProduct.product.price' => function ($query) use ($paymentMode) {
$query->where('scheme_id', $paymentMode->scheme_id);
}])->first();
$price = $stock->orderProduct->product->price;
This doesnt work as it is bad practise and i rewrote the query like below, which brings me wrong results.
$stock = Stock::whereHas('orderProduct.product.prices')
->with([
'orderProduct.product' => function ($query) {
$query->where('id', $pharmacyEvent->prescription->product_id);
},
'orderProduct.product.price' => function($query) {
$query->where('scheme_id', $paymentMode->scheme_id);
}
])->first();
Any advise on eloquent methods to use when i want to pass a condition based on relationships in a query will be highly appreciated. I am using lavel 5.8
I used whereHas :
$stock = Stock::whereHas('orderProduct.product', function($query) use ($pharmacyEvent) {
$query->where('id', $pharmacyEvent->prescription->product_id);
})
// ->whereHas('orderProduct.product.prices')
->with(['orderProduct.product.price' => function ($query) use ($paymentMode) {
$query->where('scheme_id', $paymentMode->scheme_id);
}])->first();
$price = $stock->orderProduct->product->price;
Having a hard time understanding how to order my Laravel model by a nested relationship.
Here are the Models.
User.php
// Has many small_groups through a pivot table
public function small_groups()
{
return $this->belongsToMany('App\Models\SmallGroup')->withPivot('type')->withTimestamps();
}
SmallGroup.php
// Has many SmallGroupLessons
public function small_group_lessons()
{
return $this->hasMany('App\Models\SmallGroupLesson');
}
SmallGroupLessons.php
// Has many SmallGroupLessonComments
public function small_group_lesson_comments()
{
return $this->hasMany('App\Models\SmallGroupLessonComment');
}
SmallGroupLessonsComment.php
// Belongs to SmallGroupLesson
public function small_group_lesson()
{
return $this->belongsTo('App\Models\SmallGroupLesson');
}
What's I'm trying to do, is pull all of the user's small groups, ordered by the most recent SmallGroupLessonComment if one exists. I've been doing some research, and it sounds like using Laravels ORM in this use case will not work. However, I'm not entirely sure on how to create the join on the nested relationship.
I tried the following, but this only pulls in the most latest SmallGroupLessonComment, however, it does not order the entire result set.
$small_groups = $user->small_groups()->with([
'small_group_lessons' => function($q) {
$q->with([
'latest_comment' => function($q) {
$q->orderBy('created_at', 'asc');
}
]);
}
])->paginate($limit);
Update
Was able to solve it via the following...
$small_groups = $user->small_groups()->with([
'small_group_lessons' => function($q) {
$q->with([
'latest_comment' => function($q) {
$q->orderBy('created_at', 'asc');
}
]);
}
])
->leftJoin('small_group_lessons', 'small_group_lessons.small_group_id', '=', 'small_groups.id')
->leftJoin('small_group_lesson_comments', 'small_group_lesson_comments.small_group_lesson_id', '=', 'small_group_lessons.id')
->orderBy('small_group_lesson_comments.created_at', 'desc')
->paginate($limit);
Update #2
The above doesn't work. I get multiple small groups back that are the same item.
Update #3
This query is pretty close, but it's just ordered by the most recent SmallGroupLesson. Ideally, we order by the SmallGroupLessonComment 🤔
$small_groups = $user->small_groups()->with(
[
'small_group_lessons' => function($q) {
$q->with('latest_comment');
$q->orderBy('created_at', 'desc');
}
],
)
->orderBy(
SmallGroupLesson::select('created_at')
->whereColumn('small_group_id', 'small_groups.id')
->orderBy(SmallGroupLessonComment::select('created_at')
->whereColumn('small_group_lesson_id', 'small_group_lessons.id')
->orderBy('created_at', 'desc')
->limit(1), 'desc')
->limit(1), 'desc'
)
->paginate();
$data=User::select('*')->leftJoin('small_group_lessons','small_group_lessons.user_id','user.id')
->ordeBy('small_group_lessons.created_at','DESC')->get();
try like this
I was able to solve it via the following. Ordering based off the latest comment now works correctly.
$small_groups = $user->small_groups()->with([
'small_group_lessons' => function($q) {
$q->with('latest_comment');
$q->orderBy('created_at', 'desc');
}],
)
->orderBy(
SmallGroupLesson::select('small_group_lesson_comments.created_at')
->join('small_group_lesson_comments', 'small_group_lessons.id', '=', 'small_group_lesson_comments.small_group_lesson_id')
->whereColumn('small_group_id', 'small_groups.id')
->latest()
->limit(1), 'desc'
)
->paginate();
I have been looking a way to group nested wheres from inside a eager loading query in Laravel, Let's say I have 3 Models, An Order, A Review, And a Product. For simplicity the Order has one Review, and one Product.
I want to get all the orders with the reviews and the product data that either buyer_rate or seller_rate is missing (I could group them in the code, no problem there). But I also want to check that the user logged in is the one that either placed the order (user_id in the Order class) or is the seller of the product (user_id inside the Product class).
The problem is that I can't find a way to tell Eloquent that I want this logic:
('reviews'.'buyer_rate' != null OR 'reviews'.'seller_rate' != null)
AND ('orders'.'user_id' == Auth::user()->id OR 'orders'.'producto'.'user_id' == Auth::user()->id)
This is my code: (But I can't make the second condition group)
My condition fails because it won't take in count the AND logic between the 2 groups.
$reviews = App\Order::with([
'review' => function ($q) {
$q->Where(function($query) { // Group Where buyer or seller's rate is missing.
$query->Where('buyer_rate', '!=', null);
$query->orWhere('seller_rate', '!=', null);
});
},
'producto' => function ($q) {
$q->select('id', 'user_id', 'nombre', 'precio', 'descripcion')
->orWhere('user_id', Auth::user()->id);
},
])
->orWhere('user_id', Auth::user()->id)
->get();
I think you need to use whereHas (which in turns uses an exists query). If you only use with, you're still getting every Order regardless. You're only filtering which related Review or Product are eager loaded.
Using whereHas or whereExists, you first filter the Order model and then load the relationships.
App\Order::where(function ($query) {
$query->where('user_id', auth()->id())->orWhereHas('producto', function ($producto) {
$producto->where('user_id', auth()->id());
});
})
->whereHas('review', function ($review) {
$review->whereNotNull('buyer_rate')->orWhereNotNull('seller_rate');
})
->with([
'review',
'producto' => function ($producto) {
$producto->select('id', 'user_id', 'nombre', 'precio', 'descripcion');
},
])
->get();
auth()->id() is the same as auth()->user()->id or Auth::user()->id
I am not able to find any perfect solution for it.
Controller:
$servicerequest = ServiceRequest::selectRaw('count(id) as totalservice,max(created_date) as last_service,service_provider_id,id,service_id,account_id,service_request,created_date')->with(['account' => function($first) use ($keyword) {
$first->select('id', 'restaurant_name')->orderBy('restaurant_name', 'DESC');
}])
->with(['serviceProvider' => function($query) use ($keyword) {
$query->select('id', 'company_name');
}])->groupBy('account_id')
->orderBy('company_name', 'DESC')
->paginate(100);
I need an order by on model relation table field and that effect on main table data. because it's and one to one relationship so no need to order by on the inside.
Like I need to the orderby whole on relations data.
Collection:
You must make join your relation table to used orderBy relation table.
You can try this code.
$servicerequest = ServiceRequest::selectRaw('count(id) as totalservice, max(created_date) as last_service,service_provider_id,id,service_id,account_id,service_request,created_date, SERVICEPROVIDERTABLE.company_name')
->join('serviceProvider', 'SERVICEPROVIDERTABLE.id', '=', 'SERVICEREQUESTTABLE.service_provider_id')
->with([
'account' => function ($first) use ($keyword) {
$first->select('id', 'restaurant_name')
->orderBy('restaurant_name', 'DESC');
}
])
//->with([
// 'serviceProvider' => function ($query) use ($keyword) {
// $query->select('id', 'company_name');
// }
//])
->groupBy('account_id')
->orderBy('SERVICEPROVIDERTABLE.company_name', 'DESC')
->paginate(100);
i hope this works.