SkysTheLimit_81 SkysTheLimit_81 - 4 months ago 17
SQL Question

How to count views of posts with CakePHP3?

I am using cakephp 3. In the controller I am using this code:

$conn = ConnectionManager::get('default');
$stmt = $conn->execute('UPDATE posts SET views = views + 1 WHERE id = '.$id.';');


is there a possibility to write this statement "cakephp-like"?

Answer

There is a possibility:

$posts = TableRegistry::get('Posts');
$query = $posts->query();
$query->update()
    ->set($query->newExpr('views = views + 1'))
    ->where(['id' => $id])
    ->execute();