2 questions about relations

Hi,

I’m quite used to type my sql commands directly, so i’m a bit disoriented when it comes to models and relations in Yii.

Question 1 :

How do you specify a relation in your model, when the columns are named differently in two tables ? Let’s say that the column project_category_id in the table projects matches the table category_id in the tables projects_categories, for example.

Question 2 :

How do you retrieve data from several tables, without using direct sql commands ?

Let’s say this : we have projects, classified in categories. We also have images, several by project, and for each project there is one image which is used to represent the project in the index view (its thumbnail so). There is a projects_categories table, with the categories names, a projects table with the projects data, and an images_projects tables with the data from the images from the projects. And that there is, in images_projects, a column named image_default which tells if it’s the thumbnail used to represent the project in the index view.

Corresponding sql would be that :


SELECT p.*, i.*

FROM projets p

INNER JOIN projets_categories c ON p.projet_categorie_id = c.categorie_id

INNER JOIN images_projets i ON i.image_projet_id = p.projet_id

WHERE c.categorie_slug = \'' . $categorie_slug . '\' AND i.image_default = 1

ORDER BY p.projet_ordre ASC, p.projet_id DESC';



Thanks

Have you read this?

http://www.yiiframework.com/doc/guide/1.1/en/database.arr

A lot of your questions should be addressed there. See also comment #970 in the comment section, which probably refers to your question 1.

For question two, once you have your correct relations established, you can do something like this:




$model = MyModel::model()->findByPk(5)->with('myRelation');


or


$criteria = new CDbCriteria

$criteria->with = 'myRelation';

$criteria->condition = 'id = 5';


$model->MyModel::model()->findByPk($criteria);


CVarDumper::dump($model->myRelation->myRelationAttribute, 10, true);






I read it again, and i can’t find my answer. I have the relations between categories, projects, and images, but i can’t find how to make a join between the three, and get projects and related images data in one move.

Based on your SQL, you’ll use kind of:


$model = Project::model()->with('images', 'categories')->find($yourSearchCriteriasHere);

But it’s described on AR-description page, link to which was provided by Narretz.

Please provide your code if it’s still unclear to give you more definite example based on what you already did, as my example is just a basic prototype.