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/
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.
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.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community