SQL Query: get i am trying to count unique views in my project and i got this error , I've looked it up and yet couldn't find any solution so here is the code that I've changed in the Controller before the error comes up :
class PostsController extends AppController {
public $helpers = array('Html', 'Form');
public function index()
{
$posts = $this->Post->find()
->contain(['View'])
->all();
$this->set('posts', $posts);
}
public function initialize()
{
parent::initialize();
$this->loadModel('Post');
$this->loadModel('View');
}
public function view($id)
{
$post = $this->Post->get($id);
$userId = $this->Auth->user('id');
$view = $this->View->find()
->where(['post_id' => $id, 'user_id' => $userId])
->first();
if (!$view) {
$view = $this->View->newEntity([
'post_id' => $id,
'user_id' => $userId,
'referrer' => $this->referer(),
'ip_address' => $this->request->clientIp(),
'user_agent' => $this->request->header('User-Agent')
]);
$this->View->save($view);
$post->views += 1;
$this->Post->save($post);
}
$this->set(compact('post'));
}
}
And here is the code in the post model :
public function incrementViews($id)
{
$post = $this->findById($id);
if ($post) {
$this->id = $id;
$this->saveField('views', $post['Post']['views'] + 1);
}
}
and now the view model :
<?php
// src/Model/View.php
namespace App\Model;
use Cake\ORM\Table;
class View extends Table
{
public function initialize(array $config): void
{
$this->setTable('views');
$this->belongsTo('Posts');
$this->belongsTo('Users');
}
}
any ideas ??