PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, February 2, 2022

[FIXED] Retrieve all record with a custom condition from controller

 February 02, 2022     cakephp, cakephp-2.3     No comments   

Issue

I have a simple question, but I'm stuck!

I have 2 model classes, Item and Typology.

  • Typology belongs to Item
  • Item has many Typology

Tables are like this.

TYPOLOGY: id | item_id | title | description | published
ITEM:     id | title | price | created | published

So what I want to retrieve is:

  • find all typologies WHERE published = 1 and item to which they belong has published = 1.

In the TypologyControllers I have written this code:

$typologies = $this->Typology->find(
'all', 
array(
'contain' => array(
'Item' => array(
'conditions' => array(
'Item.published =' => "1"))), 
'conditions' => array(
'Typology.published'=>'1'), 
'recursive' => -1, 
'order' => array(
'Typology.' . $this->Typology->primaryKey . ' DESC')
));


    $this->set('typologies', $typologies);  

Solution

why you dont use a joins:

$typologies = $this->Typology->find('all', array(
         'joins' => array(
            array(
                'table' => 'items',
                'alias' => 'Item',
                'type' => 'LEFT',
                'conditions' => array(
                'Item.id = Typology.item_id'
                )
            )
        ),
            'conditions' => array(
            'Item.published' => 1, 
            'Typology.published' => 1 
        ),
            'order' => array(
            'Typology.id' => 'DESC'
        ),
            'fields' => array('Item.*', 'Typology.*'),
            'recursive' => -1
        ));


    $this->set('typologies', $typologies); 


Answered By - CoolLife
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing