redGREENblue
redGREENblue

Reputation: 3126

Query issue in Yii

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?

Upvotes: 0

Views: 882

Answers (3)

Shekhar
Shekhar

Reputation: 807

Here you have many to many relationship where one product can belong to multiple categories and one category can belong to multiple products.

You will definitely need a third table

    Product Table
-------------
id
product_name
product_desc
product_color
product_price


Category Table
--------------
id
category_name


Product_Category Table
----------------------
product_category_id
product_id ( foreign key to Product->id )
category_id (foreign key to Category->id )

Upvotes: 1

stratosgear
stratosgear

Reputation: 962

Arfeen's solution is perfectly valid.

Although, I would assume that you have already read the official Relational Active Record documentation on yii website.

Upvotes: 0

Arfeen
Arfeen

Reputation: 2623

You can implement simple query without having a model like this:

$connection=Yii::app()->db;
$sql = "SELECT .....";
$command = $connection->createCommand($sql);            
$dataReader=$command->query();          
$rows=$dataReader->read();
print_r($rows);

Upvotes: 0

Related Questions