Multiple relations to the same model
Hi Thanks for your support.
I am learning cakephp by practicing from the manual.
http://book.cakephp.org/view/851/Multiple-relations-to-the-same-model
I have a message model like this
<?php
class Message extends AppModel {
var $name = 'Message';
var $belongsTo = array(
'Sender' => array(
'className' => 'User',
'foreignKey' => 'user_id'
),
'Recipient' => array(
'className' => 'User',
'foreignKey' => 'recipient_id'
)
);
}
?>
I am trying to implement the add (send message) functionality on the apps.
I have a user controller which will do the registration and auth ,...
User will login to the system and then point to /message/new/
I need to put the current username to sender_id and the user will type the email address of recipient (but in database, it is the user_id of recepient) so there is a need to change or do a findByUsername() and change it to user id when I am saving the date. First of all is this right assumption or How should I do it. I tried to something like
$recipient=$this->User->findByUsername($this->data['Message']['recipient']);
$this->Message->data['Message']['recipient_id'] = $recipient['User']['id'];
from the Message_controller I am getting an error
Fatal error: Call to a member function findByUsername() on a non-object
Here is my view,
views/messages/new
<?php
echo $session->read('Auth.User.username');
echo $session->flash('auth');
echo $form->create('Message', array('action' => 'transfer'));
echo $form->input('recipient', array('size' => '40'));
echo $form->input('body', array('size' => '40'));
echo $form->submit();
echo $form->end();
?>
I am also new to MVC I have another question where should I implement the new message action ? should it be in User controller or in message controller ? as I understood It should be in Message controller. am I right?
Would you please help me in detail how I should Implement this functionality.
any idea , link , documentation would be helpfull.
Thanks
Asked by omidzaman, on 12/7/10
1 Answer
$this->User->findByUsername($this->data['Message']['recipient']);
This line is incorrect. Your MessagesController doesn't really know what a "User" is, hence the problem. You need to use:
$this->Message->User->findByUsername($this->data['Message']['recipient']);
Otherwise, your logic seems fine by me.
And yes, the new message action should be in the messages controller. You are making a new message, and that has little to do with a user.
Also, I assume you have looked at this already, but this describes how to save the new message you just created: http://book.cakephp.org/view/75/Saving-Your-Data
Answered by deathauon 13/7/10
Thanks that worked but I neede to change that line based on my message model which should be
$this->Message->UserRecipient->findByUsername($this->data['Message']['recipient']);
omidzaman - on 13/7/10
Tagged with
Rating
0
Viewed
190 times
Last Activity
on 13/7/10