dimanche 22 décembre 2019

Laravel: Display parent value based on child tables values

In my laravel application I am facing a situation where I need to show the list of records in the grid format. However, one of the columns, called read, which is dependent on the child table's records count.

Tables:

comments:
    id, user_id, comment, post_date

comment_replies:
    id, comment_id, reply, is_read (default false)

If the comment_replies table's is_read column has at least one false value then the grid column read must be unread else "read" for the respected record.

My current code

class Comment extends Model
{
    public function index()
    {
        # fetching data
        $modelSelf = self::select([
            "comments.id",
            "comments.user_id",
            "comments.comment",
            "comments.post_date",

            \DB::raw("(
                SELECT COUNT(1) FROM `comment_replies`
                WHERE `comment_replies`.`comment_id` = `comments`.`id`
                AND `comment_replies`.`is_read` = false
            ) AS read")
        ])->paginate(15);

        # return
        return !($modelSelf->isEmpty())
            ? $modelSelf
            : null;
    }
}

Am I doing it the right way or is there any batter way to do it..?
Can it be done via relationship..?





Aucun commentaire:

Enregistrer un commentaire