tags:

views:

120

answers:

3

I have two separate controller, view, database combos: Users and Jobs. Users contains: id, name, jobid. Jobs contains: id, name, wage.

In my user container, I want to retrieve my job name and wage to send to the user view. I wanted to know what is the best practices here. I have tried two methods:

1.) $this->requestAction('/Jobs/getArray', array('pass' => user['jobid'])); I heard this is not the best practice, especially if you have a lot of interaction between controllers, which I probably will. It is also a pain to try and do all of the sending and receiving this way.

2.) App::import the jobs Connector. $Jobs = new JobsConnector. $Jobs->getArray($user['jobid']); Any time I try to do this, I get undefined errors. JobConnector::Job does not exist. I then get an error on the find() method, which otherwise is working.

I have spent hours trying to work out both methods and have been pulling my hair out. I am on the verge of going back to my own personal class interaction because of how much of a PitA these class interactions are.

Someone, please help!

A: 

Have you tried doing this with table relations instead of request actions? That way you get the related data from one model in the referencing model throughout your app.

Selino
A: 

To expand on what Selino is saying, do you have associations configured? Perhaps a User would $hasOne = array( 'Job' )? If so, then in your UsersController you can access the Job model as $this->User->Job->find( ... ).

Check out the associations documentation at http://book.cakephp.org/view/78/Associations-Linking-Models-Together. There are some good examples in there.

Rob Wilkerson
Yes, it looks like you should associate your models together. However (and this is just a preference thing), I would define the relationship as Jobs belongsTo User, which would mean having a user_id column in your jobs table. Just seems more semantic to me. Unless your data models are conceptually built on the Job being the main unit; typically I think of a User as the main building block.
Travis Leleu
A: 

I will answer assuming you have a good reason to NOT HAVE ASSOCIATIONS between your two models. If there is a reason to associate them then some of the previous answers are indeed correct.

If you don't have a valid relationship and don't want to join your models in any way then fetching via requestAction is an absolutely correct solution.

Google for "Resuable elements with requestAction" and you will get a bakery article on how to have your elements fetch their own data and cache their own data accordingly.

Mark Story did a post on the performance issues and as long as you don't abuse it, and you cache logically the performance hit is negligible.

Abba Bryant