Laravel 5.1: Eloquent relationship hasmany, Limit records - laravel-5

I have a problem with Laravel 5.1: Eloquent relationship hasmany, Limit records I have 2 tables: feeds, comments. The request is to obtain 5 feeds and comments accordingly to each particular feed. I am currently using the below query:
public function getFeed($user_id){
return Feed::whereUserId($user_id)->with(['comments'])->take(10)->get()->map(function ($feed) {
$feed->comments = $feed->comments->take(5);
return $feed;
});
}
However, it returns all the comments.
My thinking was that the $feed->comments = $feed->comments->take(5); line doesn't work. I only want to get 5 comments for each feed, do you have any advise? Any comments are highly appreciated. Thank you!

It's better late than never, I was facing the same issue yesterday and ended up by sets the entire relations array on the model.
So in your case it will be like this:
return Feed::whereUserId($user_id)->take(10)->get()->map(function($feed) {
$feed->setRelation('comments', $feed->comments->take(5));
return $feed;
});

I was facing the same issue for over a month now. I just wanted to optimize the query because it was taking almost 1.5 sec to load desired data from 1 million records.
I leveraged Eloquent ORM Collection Load() method. This reduces the load time to just 300 ms.
In your case,
return Feed::whereUserId($user_id)
->get()
->each(function ($feed) {
$feed->load('comments')->take(5);
})
});

If it's something that will apply in all cases, you can adjust the relationship in the Feed model like this:
public function comments() {
return $this->hasMany('App\Comment')->limit(5);
}

$feed= Feed::whereUserId($userId)->with(['comments'])->get()->map(function ($query) {
$query->setRelation('comments', $query->comments->take(10));
return $query;
});

Feed::whereUserId($user_id)->with([
'comments' => function($query) {
// You should limit the comments by editing the
// relationships query not the main query.
$query->take(5);
}
])->take(10)->get();
This way you can limit the feed count you want and the comment count each feed has.

the take() eloquent method just adds 'limit' word at the end of the query. this type of query is more complex and isn't supported by vanilla eloquent.
fortunately, there is an additional package called eloquent-eager-limit, which helps with this problem. in order to make it work, install that package by using composer require staudenmeir/eloquent-eager-limit command and put use \Staudenmeir\EloquentEagerLimit\HasEagerLimit; line inside both parent and children model classes.

The error might be here
$feed->comments = $feed->comments->take(5);
Which should be
$feed->comments = $feed->comments->take(5)->get();
I will suggest you write in this way
$feed->load(['comments' => function($query){ return $query->take(5); }])

Related

Query Builder filter for multi level deep relationship in Laravel

I have a selection of plots which each belong to a development by a hasManyThrough relationship through housetypes. I want to filter these by development on their overview page. Plots has a housetype_id column and housetypes has a development_id column.
public function plots()
{
return $this->hasManyThrough(Plot::class, Housetype::class);
}
When I use my filter it returns the developments ID number as $development, I then need this to only show plots which are linked to that development.
I have looked into using whereHas or Join methods but have been unable to figure this out. Current filter scope is below. Thanks
public function scopeFilterDevelopment($query)
{
$development = request()->input('filter_development');
if ($development == "") {
return;
}
if(!empty($development)){
$query->where('development_id', $development);
}
}
If I can understand it right you wish to assert a condition on other Model, HasMany will load all the objects to the related model once the query is completed. Eloquent then binds the related model objects to each.
Try joins from Laravel instead. I feel this is what you exactly want: https://laravel.com/docs/5.8/queries#joins
I would use whereHas to filter the relationship:
YourModel::whereHas('plots', function($query) {
$query->filterDevelopment();
})->get();
I would also edit the query scope not to rely on the request global function, but instead pass the development of value as a parameter.
you have make a leftjon and then use when, you dont have to use
if(!empty($development)){
$query->where('development_id', $development);
}
this any more, you can use
->when($development=="" ? false : true, function($query) use ($development){
return $query->where('development_id', $development);
})
this is a full example
$queryBuilder = DB::table('facturas')->
leftJoin('clientes','clientes.id','=','facturas.clientes_id')->
select('facturas.estados_id as estado','facturas.numero as
numero',DB::raw('concat(clientes.nombre," ",clientes.apellido) as cliente'))->
when($estados===null ? false: true,function($query) use ($estados){
return $query->whereIn('facturas.estados_id', $estados);
})
It was a whereHas that solved this in the end! (another developer at work walked me through this)
Relationship -
public function housetype()
{
return $this->belongsTo(Housetype::class);
}
Function -
public function scopeFilterDevelopment($query)
{
if (request()->input('filter_development') == "") {
return;
}else{
$query->whereHas('housetype', function($housetype){
$housetype->where('development_id', request()->input('filter_development'));
});
}
}
This then returns any plot where its housetype has a matching development_id for the filter_development from the request.
Thanks for everyone's input

Laravel / Eloquent: Is it possible to select all child model data without setting a parent?

I have various parent/child relationships, drilling down a few levels. What I want to know is if its possible to do something like this:
$student = Student::find(1);
$student->bursaries()->enrolments()->courses()->where('course','LIKE','%B%');
(With the end goal of selecting the course which is like '%B%'), or if I would have to instead use the DB Query builder with joins?
Models / Relationships
Student:
public function bursaries() {
return $this->hasMany('App\StudentBursary');
}
StudentBursary:
public function enrolments() {
return $this->hasMany('App\StudentBursaryEnrolment');
}
If what you want is to query all courses, from all enrollments, from all bursaries, from a students, then, unfortunately, you are one table too many from getting by with the Has Many Through relationship, because it supports only 3 tables.
Online, you'll find packages that you can import / or answers that you can follow to provide you more though of solutions, for example:
1) How to use Laravel's hasManyThrough across 4 tables
2) https://github.com/staudenmeir/eloquent-has-many-deep
Anyhow, bellow's something you can do to achieve that with Laravel alone:
// Eager loads bursaries, enrolments and courses, but, condition only courses.
$student = Student::with(['bursaries.enrolments.courses' => function($query) {
$query->where('course','LIKE','%B%');
}])->find(1);
$enrolments = collect();
foreach($student->bursaries as $bursary) {
$enrolments = $enrolments->merge($bursary->enrolments);
}
$courses = collect();
foreach ($enrolments as $enrolment) {
$courses = $courses->merge($enrolment->courses);
}
When you do $student->bursaries() instead of $student->bursaries, it returns a query builder instead of relationship map. So to go to enrolments() from bursaries() you need to do a bursaries()->get(). It should look like this.
$student->bursaries()->get()[0]->enrolments(), added the [0] because im using get(), you can use first() to avoid the [0]
$student->bursaries()->first()->enrolments()
But I'm not sure if it will suffice your requirement or not.

Why loadCount() introduced and its actual usage into laravel

I already read doc here :
https://github.com/laravel/framework/pull/25997
What i want to know is by using withCount() we were just load count of records instead of getting all relations data.
So by using loadCount() what we can do ?
Please explain in short in simple words.
Thanks
loadCount Eloquent Collection Method introduced by the release of Laravel 5.7.10. According to the laravel-news.
loadCount is the ability to load relationship counts on an Eloquent collection. Before this feature, you could only load relationships, but now you can call loadCount() to get counts for all relations.
The pull request illustrates how you could use loadCount() with the following example:
$events = Event::latest()->with('eventable')->paginate();
$groups = $events->map(function ($event) {
return $event->eventable;
})->groupBy(function ($eventable) {
return get_class($eventable);
});
$groups[Post::class]->loadCount('comments');
$groups[Comment::class]->loadCount('hearts');
return new EventIndexResponse($events);

Laravel eloquent query with sum of related table

I have a table users and posts with columns user_id and post_views.
In post_views I keep information how many times post was display.
And now, in query I would like to get user with sum of post_views all his posts.
I tried do something like this:
User::where(['id'=>$id])->with('posts')->get();
And in model I defined:
public function posts()
{
return $this->hasMany('App\Models\Post')->sum('post_views','AS','totalViews');
}
But without success.
How to do it?
Thank you
You can use a modified withCount():
public function posts()
{
return $this->hasMany('App\Models\Post');
}
$user = User::withCount(['posts as post_views' => function($query) {
$query->select(DB::raw('sum(post_views)'));
}])->find($id);
// $user->post_views
You can use
User::withCount('posts')->find($id)
to get the user with the id $id and a posts_count attribute in the response
I'm not fully sure what the intention of ->sum('game_plays','AS','totalVies'); is - you would need to add more context if you want this
Just something to add with regards to your shown code: No need to query by id using where + the get() at the end will make you query for a collection. If you want to get a single result use find when searching by id
As always laravel has a method for that : withSum (Since Laravel v8)
Note : I know that at the time of the message was posted, the method did not exist, but since I came across this page when I was looking for the same result, I though it might be interesting to share.
https://laravel.com/docs/9.x/eloquent-relationships#other-aggregate-functions
In your case it should be :
$user = User::withSum('posts as total_views', 'post_views')->find($id);
Then you can access to the result :
$user->total_views

Laravel - latest record from relationship in whereHas()

This is my first post in here, so please forgive any mistakes :)
I'm currently working on the project of stock management application (Laravel). I came to the point where anything I do doesn't work, so now I beg for help with it.
I have a table with products, of which some are in the relationship with the others. Everything happens in one table. If the product has a child, the child overrides the parent.
products table view
Then, all the queries I run on them use the following logic:
If the item doesn't have any child, use it.
If the item has children, use the latest child (highest id)
Now I have the relationships created in model file:
public function childItems(){
return $this->hasMany('\App\OrderItem','parent_id');
}
public function parentItem(){
return $this->belongsTo('\App\OrderItem','parent_id');
}
public function latestChild(){
return $this->hasOne('\App\OrderItem','parent_id')->orderBy('id','desc')->limit(1);
}
The problem with latestChild() relationship is, that when you run this query:
\App\OrderItem::find(7)->latestChild()->get()
It works fine and returns only one (latest)(id 6) record in relationship - to do it I had to add orderBy and limit to hasOne().
But when I want to use this relationship in scopes, so in whereHas method, it doesn't work properly, as takes any of the children instead of the latest one.
public function scopeDue($query){
return $query->where(function($q){
$q->has('childItems','==',0)->has('parentItem','==',0)->whereDate('due_date','=', Carbon::today()->toDateString())->whereNull('return_date');
})->orWhere(function($q2){
$q2->has('childItems')->has('parentItem','==',0)->whereHas('childItems',function($q3) use($q2){
$q3->whereDate('due_date','=', Carbon::today()->toDateString())->whereNull('return_date');
});
})->with('latestChild');
}
However, with() at the end returns the right record.
I think, the reason it works so is because my relationship latestChild() returns all the children (despite hasOne()) and when i use it in whereHas it ignores the filtering functions I applied.
I know it's a little bit complex from what I describe, but to explain it better I will use an example. Executing the following in tinker
\App\OrderItem::due()->get();
Should return only record id 2, as the number seven has children, where of course id 5 is due, but the latest child is id 6 which is not due.
I hope I've explained it enough to let you help me, as I'm already going crazy with it.
If you have any ideas on how I could achieve what I need by changing exisiting one or changing the whole logic of it, please help!
Thanks,
Darek
Try this one:
->with(
[
'latestChild' => function (HasOne $query) {
return $query->latest('id')->limit(1);
}
]
);
I think the problem is in your latestChild() method where you do a limit(1). Why don't you try the last() method instead?
So:
public function latestChild(){
return $this->hasOne('\App\OrderItem','parent_id')->last();
}
EDIT:
What about returning the value like this:
public function latestChild(){
$item = App\OrderItem::all()->last();
return $item;
}

Resources