Hi, i am trying to get data from 2 table (products, categories), but unable to get both tables data. The relationship is ONE-TO-MANY. Here is the relationship code in Product Model
class Product extends CActiveRecord
{
public function relations()
{
return array(
'cat' => array(self::BELONGS_TO, 'Categories', 'catid'),
);
}
}
Relationship code in Category Model
class Categories extends CActiveRecord
{
public function relations()
{
return array(
'products' => array(self::HAS_MANY, 'Product', 'catid'),
);
}
}
I think your code should work as it is, if in fact the primary key of the Categories table is ‘id’. I’m afraid you don’t have ‘id’ column in Categories table.
BTW, I would code like the following:
$criteria = new CDbCriteria();
$criteria->with = array('cat');
$criteria->compare('cat.id', $categoryid);
// or
// $criteria->compare('t.catid', $categoryid);
$criteria->order = "t.id";
$category_prods = Product::model()->findAll($criteria);
No need to set the alias ‘p’ for Product table. Yii will use ‘t’ for the main table by default. (Of course you may use the alias ‘p’ for it if you want. It’s a personal preference.)
‘compare’ is always convenient and safe to use, because it automatically uses the parameter binding. It’s the short-cut for
No need to set ‘together’ to true, because it is a BELONGS_TO relation.
There’s no need to define a property for a field of Categories table in Product model, unless if you want to search and/or sort by it. You can access the category name by the syntax of ‘$prod->cat->name’.