Faustino Gagneten
Faustino Gagneten

Reputation: 2774

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 it isn't working, I don't know how to display the query result. How can I have the code to working right? Thanks!

Upvotes: 0

Views: 604

Answers (4)

Jacek B Budzynski
Jacek B Budzynski

Reputation: 1413

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)); 
}

Upvotes: 1

Gorakh Yadav
Gorakh Yadav

Reputation: 302

I do not understand why do you pass $pots in( $query = $posts->find()).

public function index()
{
$posts = $this->Post->find('all', ['conditions' => ['userfk' => 1]]);

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

//print_r($posts);you can print array.

}

Upvotes: 0

Sonu Verma
Sonu Verma

Reputation: 86

Load Model before use in function

Please use in controller

public function initialize() {
        parent::initialize();
        $this->loadModel('Posts');
}

Then Index function:-

public function index()
{
$posts = $this->Posts->find('all', ['conditions' => ['userfk' => 1]]);

$this->set('posts',$posts);
//pr($posts->toArray());// Print Posts array
}

Upvotes: 0

Joshua Belarmino
Joshua Belarmino

Reputation: 546

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

    //or you can use dynamic finders
    $query = $posts->findByUserfk(1);

    $this->set('post', $query);
}

in your view. print all result;

pr($post);

or you can use foreach to iterate the result

foreach($post as $i => $val) {
    echo $val->userfk;
}

Upvotes: 0

Related Questions