Query Problem

Yii beginner here. I am facing some problem with how to query the database with the scenario I have. Here is what my two tables look like. The reason category is maintained in a separate table is because a product can belong to multiple categories.

Product Table


id

product_name

product_desc

product_color

product_price

Category Table


id

product_category

product_id

(A product can belong to multiple category.)

Now, let’s say I want to find the products of category ‘xyz’ with color ‘blue’. I am not sure how do I query both the tables using two different models (or not) to achieve this. Any help?

As I understand you need many to many relation, so you need something like this:

2275

relation.png

If you generate models you can run now this:




$data = Product::model()->with(

	Array('categories' => 

		Array(

			'condition' => 'categories.name = :cname', 

			'params' => Array(':cname' => 'c1')

		)

	))->findAll('color = :c', Array(':c' => 'blue'));



Hope it will help you :)

please carefully read what i post here, suppose i have two table: category and content where primry key table is category and relational table is content. now i want to assign a content to one or several categories (that is exactly you want i hope), so for this to happen,

in your content model add relation with this:




 public function relations()

	{	

		return array(

			'cate' => array(self::BELONGS_TO, 'Category', 'cate_id'),

		);

	}



and in your category model add relation with this:


public function relations()

	{

		return array(

			'contents' => array(self::HAS_MANY, 'Content', 'cate_id'),

		);

	}

and in your content model’s view/_form.php , add this:


echo $form->checkBoxList($model, 'cate_id', CHtml::listData(Category::model()->findAll(), 'id', 'cate_name'));

and in your contentController/actionCreate function , add this:


public function actionCreate() {

$model = new Content;

$this->performAjaxValidation($model);


if (isset($_POST['Content'])) {

$model->attributes = $_POST['Content'];

foreach ($_POST['Content']['cate_id'] as $categoryId) {

$postCategory = new Content;

$postCategory->cate_id = $categoryId;

$postCategory->subject_title = $model->subject_title;

$postCategory->subject_desc = $model->subject_desc;

if (!$postCategory->save())

print_r($postCategory->errors);

}


$this->redirect(array('admin'));

}


$this->render('create', array(

'model' => $model,

));

}

thats it, now if anything i missed, please knock me, i also want to learn YII professionally , thanks again ::)