Condition With Belongs_To

Hi,

I am going through a problem that how to add condition for a BELONGS_TO model for example there are two model A and B

relation is A===== BELONGS_TO====== B

now i want to create a criteria and have a search for model B with condition A.<field> = value

[b]

[/b]

[b]

[/b]

Anyone having idea how to impose condition on a model for a related model in controller ?

Thanks in advance.

First, let assume there are two table: post and category. category is the master and post the details table.




// category table structure

CREATE TABLE `category` (

  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

  `name` varchar(100) NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ;


// post table structure

CREATE TABLE `post` (

  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

  `category_id` int(10) unsigned NOT NULL,

  `user_id` int(10) unsigned NOT NULL,

  `title` varchar(255) DEFAULT NULL,

  `body` text NOT NULL,

  `date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,

  `date_updated` datetime DEFAULT NULL,

  `is_visible` bit(1) NOT NULL,

  PRIMARY KEY (`id`),

  KEY `fk_post_1` (`category_id`),

  KEY `fk_post_2` (`user_id`),

  CONSTRAINT `fk_post_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),

  CONSTRAINT `fk_post_1` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;





// Category model

class Category extends CActiveRecord

{

   public function relations()

   {

      return array(

         'posts' => array(self::HAS_MANY, 'Post', 'category_id'),

      );

   }

}


// Post model

class Post extends CActiveRecord

{

   public function relations()

   {

      return array(

         'category' => array(self::BELONGS_TO, 'Category', 'category_id'),

      );

   }

}


// Post controller

class PostController extends Controller

{

   public function actionDisplay()

   {

      // if you want to set a condition to the post table

      $models = Post::model()->with('category')

                             ->findAll('is_visible = 1');


      // if you want to set a condition to the category table

      $models = Post::model()->with(array('category'=>array('condition'=>'id = 1')))

                             ->findAll();


      // if you want to set a condition to the category and post table together

      $models = Post::model()->with(array('category'=>array('condition'=>'id = 1')))

                             ->findAll('is_visible = 1');


      $this->render('display', array('models'=>$models));

   }

}


// view file (display.php)

<div class="xyz">

   <?php

      foreach($models as $model)

      echo('Title: '.$model->title.'<br>Category: '.$model->category->name.'<hr>');

   ?>

</div>



Thanks but i found answer like you by some google but i want it by an object of CDbCriteria which i could use with CActiveDataProvider