Skip to content

How to count optimal data relations #1801

Closed
@trungdiep92

Description

@trungdiep92

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

#1339
#1147
#1416

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

#1123
#1693

How to get count from table relation???

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions