Powered by Invision Power Board



  Reply to this topicStart new topicStart Poll

> Reading name using city_id in the user (main) tabl, Reading name from id in the main table
bluesclues9
Posted: Feb 20 2012, 09:48 PM
Quote Post


Member
**

Group: Members
Posts: 11
Member No.: 2721
Joined: 3-March 11



Hi
Must be a simple one. I want to use cakephp model behaviour to do this. Can you help?

I have a user table which stores id(s) for city, secretquestion etc., so my 'user' table has city_id and secretquestion_id and the actual names/texts for these are stored in City & Secretquestion tables respectively.

Now, I am coding UsersController. When I read my User table, I get these IDs obviously. But I need to retrieve these names (City Name, Secretquestion Text) for subsequent use.

How can I do that? Can someone shed light on the steps involved?

I can simply write a SQL and do that but I want to utilize CakePHP Model functionality and handle this the CakePHP way.

Thanks
-BC
PMEmail Poster
Top
Vapour0
Posted: Feb 21 2012, 11:04 AM
Quote Post


Advanced Member
***

Group: Members
Posts: 43
Member No.: 3251
Joined: 2-December 11



You need to look at associations...
http://book.cakephp.org/2.0/en/models/asso...s-together.html

Basically, from your post, it sounds like your associations will be like.

User belongsTo City
User belongsTo SecretQuestion

Then in your model, when you
$this->User->find('all');

It will also return the matched results for City / Secret.

I haven't tested the code, but you do need associations.
PMEmail Poster
Top
bluesclues9
Posted: Feb 23 2012, 06:56 PM
Quote Post


Member
**

Group: Members
Posts: 11
Member No.: 2721
Joined: 3-March 11



Hi
Yes, it works.

I added this to my model. That's all it took.

I thought this works only when my primary table's id is placed in the secondary table as foreign key unlike in my case where I have seconday table id is in the primary table.



+++++++++++++++++++++++++++++++++
var $belongsTo = array(
'Secretquestion' => array(
'className' => 'Secretquestion',
'foreignKey' => 'secretquestion_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
+++++++++++++++++++++++++++++++++
PMEmail Poster
Top
Vapour0
Posted: Feb 23 2012, 09:26 PM
Quote Post


Advanced Member
***

Group: Members
Posts: 43
Member No.: 3251
Joined: 2-December 11



Glad to of helped :-)
PMEmail Poster
Top
0 User(s) are reading this topic (0 Guests and 0 Anonymous Users)
0 Members:

Topic Options Reply to this topicStart new topicStart Poll

 

Disclaimer:
This forum is in no way affiliated with the Cake Software Foundation
The CakePHP name and icon is a trademark of the Cake Software Foundation


Lo-Fi Version