Sub_categories[has its own id and main_category_id fields]
Items[has its own id and sub_category_id fields]
I need all items on main_category id =1,so I have two joins i.e(items INNER JOIN sub_cat)INNER JOIN(Categories)…
This SQL query works okay for me :
SELECT * FROM items i INNER JOIN sub_categories sc ON sc.id = i.sub_category_id INNER JOIN categories c ON c.id = sc.main_category_id WHERE sc.main_category_id = 1…
[*]Your setup could be better handled via relation selections what are your relations atm? for example if you have a relation:
#
# this is invalid yii code
#
#in Item->relations():
'sub_cat' => ( BELONGS_TO sub_category );
'cat' => ( BELONGS_TO category );
#you would just need
$items = Item::model()->with('sub_cat')->findAll(array('where') => cat_id = $passed_id);
to get the same results.
this way you would get an array of Item obj where item.sub_cat will be an instance of the sub_category.
[*]why have two tables for categories? I usually create one categoory table that has a self referencing fk named parent. this way anytime you create a category you can assing an allready existing subcategory to it. This way you can have infinite depth sub categories and your queries get much more consice. If you need more info let me know and I will dig up some sample code.
Thanks a lot for the reply, i’m sorry for such a late reply from my side…since the SQL queries were working, I started working on other functions and almost forgot this…
As for the 2nd part of your post…Your logic is great, It never came to my mind! It should save a lot of effort… I’ll definitely keep that in mind for future!! Thanks!