Chaining "Count of Columns" of a Method to Single Query Builder
Ad
I have set models properly and I can use this and return as json.
$profile = Profile::with('user')->find($id);
I can also add ->with('likes')
to the chain and get all the like objects. However, what I want to do is get the count of the like rows (i.e total no. of likes = total no. of rows). I know I can use a separate query with ->count()
, and add it manually to the $profile variable, but what is the way of making the call in one query?
What is the way of achieve this properly?
My dummy trial:
$profile = Profile::with('user')->with(likes.count)->find($id);
Ad
Answer
Ad
You don't need to specify anything, since Laravel returns a collection of "likes" you can use the count()
method, like so :
$profile = Profile::with(['user','likes'])->find($id);
$profile->likes->count();
More information about collections can be found in the doc
Ad
source: stackoverflow.com
Related Questions
Ad
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad