Support the ongoing development of Laravel.io →
Database Eloquent Blade
Last updated 2 years ago.
0

To avoid loading the data every time you just want a count of the records, take a look at this https://softonsofa.com/tweaking-eloquent-relations-how-to-get-hasmany-relation-count-efficiently/

0

TerrePorter said:

To avoid loading the data every time you just want a count of the records, take a look at this https://softonsofa.com/tweaking-eloquent-relations-how-to-get-hasmany-relation-count-efficiently/

That's not my issue though. My goal is to count the records of multiple models.

0

From what I understood you want to :

loop (1 or more) records from the Forum model
using the relationship Forum2Thread load the Threads for each Forum record
using the relationship Thread2Post load the Posts for each Thread record
get a count of the Posts of each thread
add the count to a tmpVar; 
repeat for next Forum model id
// --
done, tmpVar now has the total count

That sounds like your fetching all the data just to count the number of Posts.

So making a getPostsCountAttribute would be better than pulling in all of the data and doing a count on the return.

I'm assuming you have the relationships setup, you can do something like this:

$counts = Forum::all()->with('thread')->with('posts')->postsCount();
// i'm assuming that will return an array of totals for the relationship
// then you can just add them up
$total = array_sum($counts->toArray());

or at least that is the idea.

Last updated 8 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

mattrick mattrick Joined 20 Mar 2016

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.