I'm trying to use beforefind callback in ci4 BaseModel because I want to get comment like numbers for a specified post
To get post comments I'm using the normal findAll
PHP Code:
$comment_model->where('post_id', $post_id)->orderBy('id', 'desc')->findAll();
To show like numbers for each comment, I want to modify the
findAll result using a callback in
beforeFind
PHP Code:
//...
protected $beforeFind = ['beforeFindWithLikesNum'];
//...
protected function beforeFindWithLikesNum($eventData) {
$this->builder = $this->db->table($this->table);
$this->builder->select('comments.*, count(likes.id) as likenum');
$this->builder->where($this->where);
$this->builder->join('likes', 'likes.c_id=comments.id', 'left');
$this->builder->limit($eventData['limit'], $eventData['offset']);
$this->builder->groupBy('comments.id');
$this->builder->orderBy('comments.id', 'desc');
$query = $this->builder->get();
$data['data'] = $query->getResultArray();
$data['returnData'] = true;
return $data;
}
It works when I wants to get all, but when I get with condition,
PHP Code:
$model->where('post_id', 1)->findAll();
then it doesn't filter, because the "where" condition doesn't follow the eventData.
How do you think I can get where parameters inside that callback?
For now I'm using
afterFind callback looping each result but that is too many queries.
PHP Code:
protected function afterFindWithLikesNum($eventData)
{
switch ($eventData['method']) {
case 'findAll':
$like_model = new LikeModel();
foreach ($eventData['data'] as $row) {
$row['likes'] = $like_model->getCommentLikeCount($row['id']);
$rows[] = $row;
}
return ['data' => $rows];
break;
case 'find':
$like_model = new LikeModel();
$row = $eventData['data'];
$row['likes'] = $like_model->getCommentLikeCount($row['id']);
return ['data' => $row];
break;
}
Thank you