no_freedom
no_freedom

Reputation: 1961

cakephp find() question

I want to convert following mysql statement into cakephp query syntax.Please help me. Here is my query.SELECT * FROM post WHERE (user_id == $id OR awarded_to = $id ) AND id = $id

Here is my cakephp query. is it wrong.

 $this->Post->find('all', 
            array('conditions' => array('OR' =>
                                        array('Post.user_id' => $id),
                                        array('Post.awarded_to' => $id)
                                        ),
                                        'AND' =>
                                        array('Post.id' => $id)
                ))

Upvotes: 0

Views: 149

Answers (3)

Gaurav Chauriya
Gaurav Chauriya

Reputation: 303

You are very close with your query, just you need little modification like to remove 'AND' in conditions array after 'OR' as:

$this->Post->find('all', array(
        'conditions' => array(
            'OR' =>  array(
                array('Post.user_id' => $id),
                array('Post.awarded_to' => $id)
            ),
            'Post.id' => $id
        )
    ));

Or

$this->Post->find('all', array(
        'conditions' => array(
            'Post.id' => $id
        )
    ));

The second option will be the best for you if you are passing tables primary key 'id' in AND conditions.

Upvotes: 0

Onesinus Saut
Onesinus Saut

Reputation: 344

Just add Post.id = $id below the OR condition without you give "and" it's automatic read as and condition...

$this->Post->find('all', array(
         'conditions' => array(
             'OR' => array('Post.user_id' => $id),
              array('Post.awarded_to' => $id)
         ),
         'Post.id' => $id
    ));

Upvotes: 0

Dunhamzzz
Dunhamzzz

Reputation: 14808

This one's on the house, but next time read the docs.

   $this->Post->find('all', array(
            'conditions' => array(
                'OR' =>  array(
                    array('Post.user_id' => $id),
                    array('Post.awarded_to' => $id)
                ),
                'Post.id' => $id
            )
        ));

The 2 OR arrays need to be inside an array themself, and there's no need for AND.

Upvotes: 4

Related Questions