开发者

CakePHP: accessing data from query in view

I have a hasMany relationship set up. User hasMany Projects. In my users controller in the profile view I can see the projects being returned for that user in the SQL dump.

I want to display each project in my profile view for that user. So I have set up a association between user and projects. User hasMany projects. I have created a profile action in the users controller with the associated profile view. When I navigate to the profile view of one of the users with, I can see that it is querying for the projects in the SQL dump.

This is the SQL dump with the correct userid:

SELECT `Project`.`id`, `Project`.`title`, `Project`.`created`, `Project`.`website`, `Project`.`language_id`, `Project`.`user_id`, `Project`.`description`, `Project`.`tags`, `Project`.`creator_id` FROM `projects` AS `Project` WHERE `Project`.`user_id` = (5)

How can I use the data from this query?

Project Model

var $belongsTo = array(
    'User' => array(
        'className'    => 'User',
        'foreignKey'    => 'user_id',
        'counterCache' => 'num_of_projects'
        ),
    'Language'
     );  
?>

User Model

  var $hasMany = array('Project' => 
                                array('className'     => 'Project', 
                        开发者_如何转开发              'conditions'    => '',
                                      'order'         => '', 
                                      'limit'         => '',                    
                                      'foreignKey'    => 'user_id',              
                                      'dependent'     => true,                   
                                      'exclusive'     => false,                  
                                      'finderQuery'   => '',                      
                                      'fields'        => '',                      
                                      'offset'        => '',                      
                                      'counterQuery'  => ''
                                      )           
                    );

User_Controller's profile action

function profile($id = null) {
    $this->User->id = $id;
    $this->set('user', $this->User->read());
}


In your view

foreach($user['Project'] as $project)
{
   echo $project['title'].'<br />';
}

To see the bigger picture, just use pr(), you should be able to see how to access the rest of the data from there.

pr($user);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜