1

I have table like

CREATE TABLE IF NOT EXISTS `categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `parent_id` int(11) NOT NULL DEFAULT '0',
  `status` enum('1','2') NOT NULL COMMENT '''1''=active,''2''=inactive',
  PRIMARY KEY (`id`)
)

now here I want records like

id,title,parent_title,status

means I want relative title in place of parent_id(at here parent_title)

0

3 Answers 3

2

Here it is mate:

SELECT c1.id, c1.title, c2.title as parent_title, c1.status
FROM categories c1
LEFT JOIN categories c2 ON (c2.id = c1.parent_id)
Sign up to request clarification or add additional context in comments.

2 Comments

have you any idea how to do same things in cakephp?
Hey mate, sorry I don't work with cake. However you should be able to join the same entity in your Entity Manager. =)
1
$fields = array('c1.id, c1.title, c2.title as parent_title, c1.status');
        $joins = array();
            $joins[] = array(
                'table' => 'categories',
                'foreignKey' => false,
                'conditions' => 'c2.id = c1.parent_id',
                'type' => 'LEFT',
                'alias' => 'c2',
            );

$this->paginate = compact('fields', 'joins');

Comments

1

Cakephp code

In Category Controller

$fields=array(
            'Category.*',
            'ParentCategory.title'
            );
$data = $this->Category->find("all",array(
                'fields' => $fields,
                'recursive'=>0
            ));

In category Model

var $belongsTo = array(

        'ParentCategory' => array(
            'className' => 'Category',
            'foreignKey' => 'parent_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
);

2 Comments

in this case I need to create one more model 'ParentCategory'?
also I need to include this model in my controller ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.