Description
How to count optimal data relations:
Collection: photos, photos_like, photos_comment
Result: Photo i, count like, count comment
Case 1:
$photos = Photo::with(['like', 'comment' => function ($query) {
$query->where('is_approved', '1');}])
->select('photo_featured', 'title', 'view_count')->where('status', "1")->orderBy('created_at', 'desc')
->get();
view:
$photo->like->count()
$photo->comment->count()
But it selects all data in like and comment collection and then counts
->consuming memory, slow processor
Case 2: Use withCount
->return: Illegal offset type
I did not find a way to fix the error
Case 3: Use query builder and raw
$photos = DB::table('photos')
->select(['photos.photo_featured', 'photos.title', 'photos.view_count', DB::raw("COUNT(photos_like._id) as like_count"),
DB::raw("COUNT(photos_comment._id) as comment_count")])
->....
->return: Illegal offset type
error when using DB::raw
How to get count from table relation???