SQL查询:获取 我正在尝试计算我项目中的独特视图,但出现此错误,我已经查找但找不到任何解决方案,所以这是我在出现错误之前在控制器中更改的代码:
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'));
}
}
这是后期模型中的代码:
public function incrementViews($id)
{
$post = $this->findById($id);
if ($post) {
$this->id = $id;
$this->saveField('views', $post['Post']['views'] + 1);
}
}
现在是视图模型:
<?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');
}
}
任何想法??