简体   繁体   中英

How can I select count from relational table while using with laravel

I am working for a social app, I need to show feeds with tagged user, hash tags, like counts, comments count, comments and users details who has commented.

The feed is bit different from normal feed, here is the database structure.

User Table:

id username email image

Movie Table: (Admin will add the movie, and user will rate that by search a movie by title)

id title image description

Rating Table: (this will be a feed, that a user has rated x movie, while rating user will tag to another user and also use some hash tags )

id movie_id user_id rating description

rating_tag table: (it will hold the hash tags id and rating id)

id rating_id tag_id

rating_user table: (it will hold the tagged users id and rating id)

id rating_id tag_id

likes table:

id rating_id user_id

comments table:

id rating_id user_id comment

Now I need to show feed with all the stuff, rating as feed (user image who has rated, movie image, title and description) with all comments that who has commented with those users details and total like count.

I have use that but its not giving me proper result.

public function getAllForFeed ($user_ids) {
    return $this->with(['tags' => function ($q) {
        $q->select('tags.id');
    }])->with(['likes' => function ($q) {
        $q->select(DB::raw('count(id) as like_count'));
    }])->with(['comments' => function ($q) {
        $q->select('user_id', 'comment');
    }])->with(['users' => function ($q) {
        $q->select('users.id');
    }])->whereIn('user_id', $user_ids)->get()->toArray();
}

I think this can be done using relationship in each respective models and fetching data using that relations when needed.

So at first find the carnality between related tables and put relations in each models. Then try using that relations with model object. Please try to solve using relation, and if you still can not figure out then post your models with relationship and view code where you want to display your feed, I will try to solve.

I think you have a look on official documentation about eloquent relationship .If not yet, have a look.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM