Sunday, August 1, 2010

$hasOne - multiple referencing the same model / alias association

Hi,

I've got a helpdesk application that's being converted to CakePHP and
I'm trying to reference a model more than once from within a parent
model, in this case the Message model references the User model twice
- once for sender, once for reciever.

According to the Cookbook, as I have a one-to-one database
relationship (one user has one sender and one user has one reciever) I
need the $hasOne, though I've also tried using the $belongsTo with the
same amount of success.
http://book.cakephp.org/view/78/Associations-Linking-Models-Together

I've implimented according to the cookbook:
http://book.cakephp.org/view/851/Multiple-relations-to-the-same-model

The error is that the foreignKey is being applied to the aliased
JOINed 'child' table, not the parent table. I get the error (note
I've removed some of the detail):

Warning (512): SQL Error: 1054: Unknown column 'Sender.sender_id' in
'on clause' [CORE/cake/libs/model/datasources/dbo_source.php, line
673]
Code | Context
$out = null;
if ($error) {
trigger_error('<span style="color:Red;text-
align:left"><b>' . __('SQL Error:', true) . "</b> {$this->error}</
span>", E_USER_WARNING);
$sql = "SELECT `Message`.`id`, `Message`.`sender_id`,
`Message`.`receiver_id`, `Sender`.`id`, `Sender`.`name`,
`Recipient`.`id`, `Recipient`.`name` FROM `messages` AS `Message` LEFT
JOIN `users` AS `Sender` ON (`Sender`.`sender_id` = `Message`.`id`)
LEFT JOIN `users` AS `Recipient` ON (`Recipient`.`recipient_id` =
`Message`.`id`) WHERE 1 = 1 ORDER BY `name` ASC LIMIT 10"
$error = "1054: Unknown column 'Sender.sender_id' in 'on
clause'"
$out = null

My d/b structure (abridged):

Table Message
id int autonumber,
sender_id int,
recipient_id int

Table User
id int autonumber,
name varchar(100)

My code:
<?php
class Message extends AppModel
{
var $name = 'Message';
var $validate = array(
// Not relevant
);

var $hasOne = array(
'Sender' => array( // Alias name
'className' => 'User', // Class of model to link to
'dependent' => false, // No dependancies
'foreignKey' => 'sender_id' // field name in Message table
),
'Receiver' => array(
'className' => 'User',
'dependent' => false,
'foreignKey' => 'receiver_id'
)
);

var $hasMany = array
(
// Not relevant
);

var $hasAndBelongsToMany = array(
// Not relevant
);
}
?>

What am I doing wrong, in particular how can I tell CakePHP that the
foreign key is in the primary table, not the JOINed tables?

Thanks in advance,

Duncan

Check out the new CakePHP Questions site http://cakeqs.org and help others with their CakePHP related questions.

You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php?hl=en

No comments: