Toby Priest
Toby Priest

Reputation: 25

Look up data from a diffrent model using Cake

im new to cake (and loving it) but i have hit a problem that i cant seem to find a solution to. Im pretty sure there is an obvious answer to this so my apols in advance if i am asking a stupid question.

Okay, here goes.

I am trying to build a simple message system using Cake PHP version 2.

I have two models at the moment, one handles users (used for loggin in and out) and the other handles messages.

In the messages table i have the following columns:

id | sender_id | recipient_id | subject | body

My MessagesController.php reads as follows:

class MessagesController extends AppController {
 public function recent_messages() {
    if (empty($this->request->params['requested'])) {
        throw new ForbiddenException();
    }
    return $this->Message->find(
        'all'
    );
 }    
}

My View is located in my elements as it actually displayed as a drop down in my navbar. Here is my view:

<?php
 $messages = $this->requestAction('/messages/recent_messages');
?>

<?php 
 foreach ($messages as $message): ?>
  <li> 
   <a href="#">
 <div> <strong>Username of sender goes Here</strong></div>
<div><?php echo $message['Message']['subject']; ?></div>
  </a> 
 </li>
 <li class="divider"></li>
<?php endforeach; ?>

What i would like to do is to be able to get the actual username of the message sender using the sender_id. Just to clarify the sender_id value is actually the id (primary key) of the user in the users table.

Initially i thought this would be done through setting an association but i cant see how.

If anyone could offer any advice on this i would be most grateful.

Upvotes: 1

Views: 52

Answers (2)

Jerry Kita
Jerry Kita

Reputation: 25

One further thought.

It seems that you are doing the requestAction from the view. I think it can only be done from the controller and then you pass the result to the view via the $this->set('messages', $message) command.

If I've misinterpreted what you are doing then I'm sorry.

Upvotes: 0

arilia
arilia

Reputation: 9398

I don't understand why you are using $this->requestAction

if your view is recent_messages.ctp you are already calling recentMessages().

Then if you set your relationships you are already retrieving all the data you need

$message['Sender']['username']

contains the information you are looking for. (or $message['User']['username'] it depends on how you wrote your model).

If not read the Manual about setting the relationships.

In brief all you have to do in your Message model is

$belongsTo = array(
    'Sender' => array(
            'className' => 'User',
            'foreignKey' => 'sender_id'
        )
)

Upvotes: 1

Related Questions