Federick Jons Federick Jons - 5 months ago 24
SQL Question

Custom Query in Cakephp 3.0?

I want to make a custom query in Cakephp. I've been reading this: Query Builder

The problem that every example are like:

$query = $articles->find()
->where([
'author_id' => 3,
'OR' => [['view_count' => 2], ['view_count' => 3]],
]);


But in my PostController I have this:

public function view($id = null)
{
$post = $this->Posts->get($id, [
'contain' => ['Users']
]);
$this->set('post', $post);
$this->set('_serialize', ['post']);
}


I don't have anything with find(). And I don't know what is doing the last part of code

This is the query that I want to use:

public function index()
{
$query = $posts->find()->where([
'userfk' => 1
]);
}


But is not working, I don't know how to display the query result.
How can I have the code to working right?
Thanks!

Answer

If you want use Query Builder

http://book.cakephp.org/3.0/en/orm/query-builder.html

PostsController.php

public function index() {

   $posts = $this -> Posts -> find() -> where(['userfk' => 1]);

   $this -> set('post', $posts);

}

By the way, if the result get few $posts

Your set should be $this -> set('posts', $posts); and your view have

<?php foreach($posts as $post): ?>
  <!-- your code -->
<?php endforeach; ?>

/////// EDIT Adding Paginator option

PostsController.php

public function index() {

    $this -> paginate['contain'] = ['Users']; 
    $this -> paginate['conditions'] = ['Posts.userfk' => 1]; 

    $this -> set('posts' , $this -> paginate($this -> Posts)); 
}