0

I am having a problem getting a model->find() call to respect a belongsTo association I built.

Here is the association:

var $belongsTo = array('User' => array('className'  =>'User',
                                       'foreignKey' => 'id',
                                   'fields'     => array('username')
                                       )
                      );

And here is the find call:

$this->set('broadcasters_list', $this->Broadcaster->find('all',  
                                                         array('fields'=>array('id')
                                                         )));

Now for a very odd thing; I have a pagination call on the Broadcaster model that, when called, respects the belongsTo association and returns the necessary information from the User model.

take care, lee

Edit:

I took a look at the query being built, here is what I have:

For the find command:

SELECT `Broadcaster`.`id` FROM `broadcasters` AS `Broadcaster` LEFT JOIN `users` AS `User` ON (`Broadcaster`.`id` = `User`.`id`) LEFT JOIN `images` AS `profile_image` ON (`profile_image`.`user_id` = `Broadcaster`.`id` AND image_type = 3) WHERE 1 = 1 

For the pagination call:

SELECT `Broadcaster`.`id`, `Broadcaster`.`key_id`, `Broadcaster`.`session_id`, `Broadcaster`.`broadcast_mode`, `Broadcaster`.`next_guest_id`, `Broadcaster`.`one_to_one_credits`, `Broadcaster`.`one_to_many_credits`, `Broadcaster`.`avilable_for_private`, `Broadcaster`.`connect_type`, `Broadcaster`.`commission`, `Broadcaster`.`credits`, `Broadcaster`.`enabled`, `User`.`username`, `profile_image`.`file_id` FROM `broadcasters` AS `Broadcaster` LEFT JOIN `users` AS `User` ON (`Broadcaster`.`id` = `User`.`id`) LEFT JOIN `images` AS `profile_image` ON (`profile_image`.`user_id` = `Broadcaster`.`id` AND image_type = 3) WHERE `enabled` = 1 LIMIT 10

With the exception of the fields being retrieved, it all looks the same. Am I missing something in there?

tereško
  • 58,060
  • 25
  • 98
  • 150
Lee Loftiss
  • 3,035
  • 7
  • 45
  • 73

1 Answers1

0

You have the foreignKey wrong. The foreign key is the value in the current table that links to the key in the foreign table, so in this case it should be user_id

var $belongsTo = array('User' => array('className'  =>'User',
                                       'foreignKey' => 'user_id',
                                   'fields'     => array('username')
                                       )
                      );
paullb
  • 4,293
  • 6
  • 37
  • 65
  • Hello. I tried that already and it didn't work. But, even if it did, it would not explain why a pagination call would work but a find() call would not. The queries both are building are identical in the parts that deal with getting the info from User. – Lee Loftiss Jun 30 '12 at 12:10
  • I have found that Cakephp can be iffy if you don't use the defaults for foreign keys "_id" – paullb Jul 02 '12 at 02:09