cakephp error在数组中调用成员函数where()

tct7dpnv  于 2023-05-27  发布在  PHP
关注(0)|答案(1)|浏览(142)

这是我在view方法中的代码,我已经尝试了select和distinct,但仍然得到相同的错误

$uniqueViews = $this->Post->find()
    ->where(['Post.id' => $id])
    ->matching('Views', function ($q) {
        return $q->where(['Views.user_id IS NOT NULL']);
    })
    ->group(['Views.user_id', 'Post.id'])
    ->count();
    $this->set(compact('uniqueViews'));

这是我的视图方法

public function view($id = null) {
    // Get the user ID of the current user
    $user_id = $this->Auth->user('id');

    // Get the IP address of the current user
    $ip_address = $this->request->clientIp();

    // Find the post with the given ID
    $post = $this->Post->findById($id);

    // Increment the view count for the post, user ID, and IP address
    if ($post) {
        $this->Post->incrementViews($id, $ip_address, $user_id);
        $this->set('post', $post);
    } else {
        // Post not found
        $this->Flash->error(__('The post you requested could not be found.'));
        $this->redirect(array('action' => 'index'));
    }

    // Count the number of unique users that viewed the post
   

    $uniqueViews = $this->Post->find()
    ->where(['Post.id' => $id])
    ->matching('Views', function ($q) {
        return $q->where(['Views.user_id IS NOT NULL']);
    })
    ->group(['Views.user_id', 'Post.id'])
    ->count();
    $this->set(compact('uniqueViews'));

    // Throw an error if no ID is provided or the post is not found
    if (!$id || !$post) {
        throw new NotFoundException(__('Invalid post'));
    }
}
pkwftd7m

pkwftd7m1#

尝试更改此代码:

$uniqueViews = $this->Post->find()
->where(['Post.id' => $id])
->matching('Views', function ($q) {
    return $q->where(['Views.user_id IS NOT NULL']);
})
->group(['Views.user_id', 'Post.id'])
->count();
$this->set(compact('uniqueViews'));

通过这一条:

$options['conditions'] = ['Views.post_id' => $id, 'Views.user_id IS NOT NULL'];
$options['fields'] = 'DISTINCT Views.user_id';
$uniqueViews = $this->Views->find('count', $options);
$this->set(compact('uniqueViews'));

相关问题