Multiple table data get using with() - php

Here, is my eloquent
$contacts = Contact::where('property_id',$commercial->id)->where('property_type','commercial_lease')
->with('contact_log')
->with('user_name')
->with('contact_log.contact_log_name')
->get();
->with('contact_log')
with this relationship...I got each and every data from that table using ->with('contact_log'). But i want last inserted data via with relationship.
Others will remains same. But need to get only last data via this relation.

You need to apply extra constraints on your contact_log relation in order to fetch only the last entry.
Replace
->with('contact_log')
with
->with('contact_log', function($query) {
// order latest entries first
$query->orderBy('created_at', 'DESC');
// take only the first entry
$query->take(1);
})

Related

get latest record of multiple groupby laravel

I want to group by an laravel eloquent with two classes come in with() I want to add column of these two with classes in group by
$query = CourseEnrolled::with('user', 'course')->latest()->groupBy('course_id','user_id')
Here course id come from course table and user id come from user table. it successfully group columns but does sort latest record. It display old record only
I have also tried but still same result
$query = CourseEnrolled::with('user', 'course')->orderBy('created_at')->groupBy('course_id','user_id')
u cant query them directly with the eloquent model of CourseEnrolled. if you want to add additional queries with other models, you have to use with() in this way :
CourseEnrolled::with('user' , function($user){
// now u can use any query with user fields
$user->where('user-name' , 'value');
})
This query solve my problem
$query = CourseEnrolled::with('user', 'course')->latest()->whereIn('id', function($q){
$q->select(DB::raw('MAX(id) FROM course_enrolleds GROUP BY user_id,course_id'));
});

Laravel find rows by nested relationship column

I have 2 tables reserves and chats, chats belongTo reserves and I want to get all chats where chat.reserve.user_id = Auth::id(). How can I do that in laravel.
I don`t know your models name (need more code in question), but try use
$chats = Chat::query()->whereHas('reserves', function ($q) use ($authID){
$q->where('user_id', $authID);
})->get();
where 'reserves' your relationship and have field user_id. Maybe needed full path to field like 'reserves'.'user_id'
Also look at documentation

internal orderBy gets overwritten by external orderBy in Laravel Eloquent

I have a reliationship User hasOne Position and I'm fetching the users, but I want to sort them first by Position->name and then by User->name. I tried the following
<?php
$sorted = Position::where('groupId', $this->groupId)
->whereIn('id', $positions)
->with(['user' => function($query) {
$query->orderBy('user.name'); // internal sort
}])
->orderBy('position.name') // external sort
->get();
This way the results are sorted by the external sort only, or, by Position->name. Different users with the same Position->name are listed unsorted. If I remove the external sort, and leave only the sortBy User->name, it works, BUT only for the names, while positions are random.
I have tried different ways
setting the order in the Position->user relationship, does not work
setting the order in the User->position relationship, does not work
defining only an external orderBy('position.name, user.name'), crashes, saying user table is not in the query.
I also tried following similar questions like
Laravel orderBy on a relationship
Ordering Related Models with Laravel/Eloquent
but they don't seem to be trying to sort the results both by the parent and the relationship. It seems my only solution is to walk the result and sort them in PHP instead of from the DB, but this sounds dumb.
Please advice, thank you.
When you want to sort the parent Position by the relationship User, you need to use a join():
$sorted = Position::where(...)
->whereIn(...)
->with('user')
->join('users', 'users.id', '=', 'positions.user_id') // Or whatever the join logic is
->orderBy('users.name')
->orderBy('positions.name')
->get();
Note: The orderBy() on the user relationship within with() doesn't seem necessary, as by convention, a singular-named relationship should only return 1 record, and sorting on a single record is pointless.
This will return a Collection of Position models, with an attached User model, sorted by the User's name, then the Position's name. You might need to add a select('positions.*') to avoid any ambiguity issues, but this should give you the general idea.

Laravel Eloquent Latest Status From Log Table

I have an order_status_transaction table which is a log table for recording the status of transactions
I am trying to write an eloquent builder to get all of the transactions with a CURRENT status of 5 for example.
This is the closest I have got
$transactions = $this->whereHas('statuses', function ($query) use ($statusId) {
$query->where('order_status_transaction.order_status_id', $statusId)->where();
});
But it does not check if it is the most recent. I don't want to get the collection and filter the collection, can this be going purely in a builder?
This should do
$transactions = OrderStatusTransaction::where('order_status_id', $statusId)->latest()->get();
Assuming OrderStatusTransaction as your model name.
As in the comments, latest sorts by latest.
Query builder has a method called latest() and so you would write something like this:
OrderStatusTransaction::where('order_status_id', $statusId)
->latest()
->get();
This will get all the records with the given status id going from most recent first to oldest.
You can read me about this here:
https://laravel.com/docs/5.7/queries#ordering-grouping-limit-and-offset

Use custom function inside eloquent orderBy() method

I have a list or products in my database that needs to be ordered based on their updated_at field. But I also want to view the products at the beginning that are missing some attributes.
For example, I want to list those products at first that are missing description or colors and then order them based on their update date. Also I want to paginate them so I cannot sort them after I retrieve all the products from database.
So is there a way to achieve this using eloquent in Laravel?
This is how my products table looks like,
products
-id
-style
-title
-description
-colors
-sizes
-cost
-weight
-created_at
-updated_at
You can use limit and skip for pagination not sure but you can use like this for your problem..
function getProdcucts($skip, $limit){
$list = DB::table('reports')->select()
->where('colors', '=', null)
->orWhere('description', '=', null)
->orderBy('updated_at', 'desc')
->skip($skip)
->limit($limit)
->get();
return $list;
}
Dont fetch all record in one time, fetch record from db according to per page items.

Categories