I have a list with messages. Its possible to reply to these messages (parent - child). I do not show child-messages in the list.
How can I always display the newest parent-message on top. Newest means that either the parent OR one of the childern has the newest timestamp.
Here is my eloquent query:
Message::withCount(['childMessages as latest_child_message' => function($query) {
$query->select(DB::raw('max(created_at)'));
}])
->orderByDesc('latest_child_message')
->orderByDesc('created_at')
->get();
Both orderBy should somehow be combined. Otherwise either the parent or the child sort will be prioritised.
In the context it's not possible to sort the collection after the DB-query.
edit 1:
Since "ee" is the latest response (child), the "bb" message should be at the bottom of the list.
edit 2:
The query will be used in a function returning a query
public static function getEloquentQuery(): Builder {
$query = parent::getEloquentQuery();
return $query->doTheMagicHere();
}
edit 3
This would be a working query.. but it's very slow
SELECT
id,
comment,
(SELECT MAX(cc.id) FROM comments cc WHERE cc.commentable_id = c.id) AS child_id
FROM
comments c
WHERE
commentable_type NOT LIKE '%Comment%'
ORDER BY CASE WHEN child_id IS NULL
THEN id
ELSE child_id
END DESC
;
In the withCount closure you must set conditions.
Use this:
Message::with('childMessages')->get()->sortByDesc(function ($parent, $key) {
$child = $parent->childMessages()->orderBy('created_at', 'desc')->first();
return $child ? $child->created_at : $parent->created_at;
});
the orderBy way you need is a bit complicated. it's better to use sortByDesc method and sort data on collection.
I hope this works.
Related
I have three models with the following hierarchy :
User
id
....some other properties
Journey
id
user_id
budget
....some other properties
Confirmation
id
journey_id
user_id
....some other properties
I have a HasMany from User to Journey, a HasMany from Journey to Confirmation.
I want to get the sum for a column of the journeys table by going through the confirmations table but I cannot create an intermediate HasManyThrough relation between User and Journey by using Confirmation.
I have tried to do
public function journeysMade(): HasManyThrough
{
return $this->hasManyThrough(Journey::class, Confirmation::class);
}
// And after,
User::with(...)->withSum('journeysMade','budget')
But it was not possible because the relations are not adapted.
With hindsight, the sql query I want to translate would look like
select coalesce(sum(journeys.budget), 0) as income
from journeys
inner join confirmations c on journeys.id = c.journey_id
where c.user_id = ? and c.status = 'finalized';
How can I implement this query considering how I will use my query builder :
$driversQueryBuilder = User::with(['profile', 'addresses']); // Here
$pageSize = $request->input('pageSize', self::DEFAULT_PAGE_SIZE);
$pageNumber = $request->input('pageNumber', self::DEFAULT_PAGE_NUMBER);
$driversPaginator = (new UserFilterService($driversQueryBuilder))
->withStatus(Profile::STATUS_DRIVER)
->withCountry($request->input('country'))
->withSex($request->input('sex'))
->withActive($request->has('active') ? $request->boolean('active') : null)
->get()
->paginate(perPage: $pageSize, page: $pageNumber);
return response()->json(['data' => $driversPaginator]);
The reason why I want to get a builder is because UserFilterService expects a Illuminate\Database\Eloquent\Builder.
Do you have any idea about how I can solve this problem ?
Not 100% sure what exactly you want to sum, but I think you need the following query
$user->whereHas('journeys', function($query) {
$query->whereHas('confirmations', function($subQuery) {
$subQuery->sum('budget);
}
});
If you the above query isn't summing the budget you need, you just add another layer of abstraction with whereHas methods to get exactly what you need. Hope this helps!
EDIT:
$user->whereHas('confirmations', function($q) {
$q->withSum('journeys', 'budget')->journeys_sum_budget;
}
I have the following tables:
orders:
- id
- date
item_order:
- order_id
- item_id
items:
- id
- desc
- price
Using Eloquent, how can I get all the items NOT included in a giving order (say, the order with id = 6)?
I'm trying to do relationships & subqueries, but without luck.
Thanks in advance.
Your question is not clear enough, Using Eloquent, how can I get all the items NOT included in a giving order (say, the order with id = 6)?, this sentence is unclear.
In other hand based on your explanation, below example gonna return list of orders with their items, except something you don't want:
$id = 6;
// Get list of orders with itemOrder.
Order::with('itemOrder' => function ($query) use $($id) {
//make sure query don't return list of order items belong to order id = 6.
$query->where('order_id', '!=,' $id)
})->get();
You will get list of orders with item_order but you will not get item_order for order with id of 6.
If this is not what you've asked please clarify and update your question for better explanation.
Based on your comment : Your solution gives me the ORDERS, but I want all the ITEMS, except those of the order with id = 6., you can simply replace query with specified model and relations
$id = 6;
Item::with('itemOrder' => function ($query) use $($id) {
$query->where('order_id', '!=,' $id)
})->get();
// Or,
// This one only return items with itemOrders and of course returned itemsOrder
// will be affected by query inside callback function
Item::whereHas('itemOrder' => function ($query) use $($id) {
$query->where('order_id', '!=,' $id)
})->get();
I have four tables technologies(id, name), tasks(id, name), requests(id, status_id, comment, task_id, created_at), technology_task(id, task_id, technology_id)
I want to get the requests whose status_id is 2 and join the tasks table which has specific technologies inserted in the technology_task pivot table. I want to group the result based on the date column created_at. Is this possible through Lravel model eloquent? I have tried the below method.
$this->model
->with('task', 'task.technologies')
->where('status_id', 2)->get()
->groupBy(function ($val) {
return Carbon::parse($val->created_at)->format('d-m-Y')
This is the Request model and this will return all the requests whose status_id is 2 along with the related task and technologies. But I only want the requests whose task have specific technologies, and I want to check that using something like ->whereIn('id', [1, 2, 3])->get()
How to achieve this using model? or do I need to use a custom query
Assuming $this->model is your Request model, and all your relationships are set correclty, you can use whereHas:
$technologyIds = [1, 2, 3];
$collection = $this->model
->with(['task', 'task.technologies'])
->whereHas('task.technologies', function($query) use ($technologyIds)
{
// here you can check using whereIn
$query->whereIn('technologies.id', $technologyIds);
})
->where('requests.status_id', 2)
->get();
If you want to use the groupBy inside the MySQL query, you will need to define what data should MySQL select when grouping. You can achieve that using aggregation functions. You weren't clear about the data you want to select, the code bellow should return:
the greatest id of the grouped rows,
unique comments concatenated with space
created_at
$technologyIds = [1, 2, 3];
$collection = $this->model
->with('task', 'task.technologies')
->whereHas('task.technologies', function($query) use ($technologyIds)
{
$query->whereIn('technologies.id', $technologyIds);
})
->where('requests.status_id', 2)
->groupBy('requests.created_at')
->selectRaw('
MAX(requests.id) AS id,
GROUP_CONCAT(DISTINCT requests.comment
ORDER BY requests.comment ASC SEPARATOR ' ') AS comments,
requests.created_at
')
->get();
Check out the docs to see how each aggregation functions works.
I have two tables, say "users" and "users_actions", where "users_actions" has an hasMany relation with users:
users
id | name | surname | email...
actions
id | id_action | id_user | log | created_at
Model Users.php
class Users {
public function action()
{
return $this->hasMany('Action', 'user_id')->orderBy('created_at', 'desc');
}
}
Now, I want to retrieve a list of all users with their LAST action.
I saw that doing Users::with('action')->get();
can easily give me the last action by simply fetching only the first result of the relation:
foreach ($users as $user) {
echo $user->action[0]->description;
}
but I wanted to avoid this of course, and just pick ONLY THE LAST action for EACH user.
I tried using a constraint, like
Users::with(['action' => function ($query) {
$query->orderBy('created_at', 'desc')
->limit(1);
}])
->get();
but that gives me an incorrect result since Laravel executes this query:
SELECT * FROM users_actions WHERE user_id IN (1,2,3,4,5)
ORDER BY created_at
LIMIT 1
which is of course wrong. Is there any possibility to get this without executing a query for each record using Eloquent?
Am I making some obvious mistake I'm not seeing? I'm quite new to using Eloquent and sometimes relationship troubles me.
Edit:
A part from the representational purpose, I also need this feature for searching inside a relation, say for example I want to search users where LAST ACTION = 'something'
I tried using
$actions->whereHas('action', function($query) {
$query->where('id_action', 1);
});
but this gives me ALL the users which had had an action = 1, and since it's a log everyone passed that step.
Edit 2:
Thanks to #berkayk looks like I solved the first part of my problem, but still I can't search within the relation.
Actions::whereHas('latestAction', function($query) {
$query->where('id_action', 1);
});
still doesn't perform the right query, it generates something like:
select * from `users` where
(select count(*)
from `users_action`
where `users_action`.`user_id` = `users`.`id`
and `id_action` in ('1')
) >= 1
order by `created_at` desc
I need to get the record where the latest action is 1
I think the solution you are asking for is explained here http://softonsofa.com/tweaking-eloquent-relations-how-to-get-latest-related-model/
Define this relation in User model,
public function latestAction()
{
return $this->hasOne('Action')->latest();
}
And get the results with
User::with('latestAction')->get();
I created a package for this: https://github.com/staudenmeir/eloquent-eager-limit
Use the HasEagerLimit trait in both the parent and the related model.
class User extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
class Action extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
Then simply chain ->limit(1) call in your eager-load query (which seems you already do), and you will get the latest action per user.
My solution linked by #berbayk is cool if you want to easily get latest hasMany related model.
However, it couldn't solve the other part of what you're asking for, since querying this relation with where clause would result in pretty much the same what you already experienced - all rows would be returned, only latest wouldn't be latest in fact (but latest matching the where constraint).
So here you go:
the easy way - get all and filter collection:
User::has('actions')->with('latestAction')->get()->filter(function ($user) {
return $user->latestAction->id_action == 1;
});
or the hard way - do it in sql (assuming MySQL):
User::whereHas('actions', function ($q) {
// where id = (..subquery..)
$q->where('id', function ($q) {
$q->from('actions as sub')
->selectRaw('max(id)')
->whereRaw('actions.user_id = sub.user_id');
})->where('id_action', 1);
})->with('latestAction')->get();
Choose one of these solutions by comparing performance - the first will return all rows and filter possibly big collection.
The latter will run subquery (whereHas) with nested subquery (where('id', function () {..}), so both ways might be potentially slow on big table.
Let change a bit the #berkayk's code.
Define this relation in Users model,
public function latestAction()
{
return $this->hasOne('Action')->latest();
}
And
Users::with(['latestAction' => function ($query) {
$query->where('id_action', 1);
}])->get();
To load latest related data for each user you could get it using self join approach on actions table something like
select u.*, a.*
from users u
join actions a on u.id = a.user_id
left join actions a1 on a.user_id = a1.user_id
and a.created_at < a1.created_at
where a1.user_id is null
a.id_action = 1 // id_action filter on related latest record
To do it via query builder way you can write it as
DB::table('users as u')
->select('u.*', 'a.*')
->join('actions as a', 'u.id', '=', 'a.user_id')
->leftJoin('actions as a1', function ($join) {
$join->on('a.user_id', '=', 'a1.user_id')
->whereRaw(DB::raw('a.created_at < a1.created_at'));
})
->whereNull('a1.user_id')
->where('aid_action', 1) // id_action filter on related latest record
->get();
To eager to the latest relation for a user you can define it as a hasOne relation on your model like
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class User extends Model
{
public function latest_action()
{
return $this->hasOne(\App\Models\Action::class, 'user_id')
->leftJoin('actions as a1', function ($join) {
$join->on('actions.user_id', '=', 'a1.user_id')
->whereRaw(DB::raw('actions.created_at < a1.created_at'));
})->whereNull('a1.user_id')
->select('actions.*');
}
}
There is no need for dependent sub query just apply regular filter inside whereHas
User::with('latest_action')
->whereHas('latest_action', function ($query) {
$query->where('id_action', 1);
})
->get();
Migrating Raw SQL to Eloquent
Laravel Eloquent select all rows with max created_at
Laravel - Get the last entry of each UID type
Laravel Eloquent group by most recent record
Laravel Uses take() function not Limit
Try the below Code i hope it's working fine for u
Users::with(['action' => function ($query) {
$query->orderBy('created_at', 'desc')->take(1);
}])->get();
or simply add a take method to your relationship like below
return $this->hasMany('Action', 'user_id')->orderBy('created_at', 'desc')->take(1);
I am trying to get a single column of an inner joined model.
$items = Item::with('brand')->get();
This gives me the whole brand object as well, but I only want brand.brand_name
$items = Item::with('brand.brand_name')->get();
DidnĀ“t work for me.
How can I achieve this?
This will get related models (another query) with just the column you want (an id, see below):
$items = Item::with(['brand' => function ($q) {
$q->select('id','brand_name'); // id is required always to match relations
// it it was hasMany/hasOne also parent_id would be required
}])->get();
// return collection of Item models and related Brand models.
// You can call $item->brand->brand_name on each model
On the other hand you can simply join what you need:
$items = Item::join('brands', 'brands.id', '=', 'items.brand_id')
->get(['items.*','brands.brand_name']);
// returns collection of Item models, each having $item->brand_name property added.
I'm guessing Item belongsTo Brand, table names are items and brands. If not, edit those values accordingly.
Try this:
$items = Item::with(array('brand'=>function($query){
$query->select('name');
}))->get();