开发者

CakePHP - Posts and Children Posts need User Data

开发者 https://www.devze.com 2023-03-26 14:56 出处:网络
I have a Post Model, like this: <?php class Post extends AppModel{ var $name = \'Post\'; // -=> One Post hasMany Children [also of type Post, where Post.parent_id == foreignKey]:

I have a Post Model, like this:

<?php
    class Post extends AppModel{
        var $name = 'Post';
        // -=> One Post hasMany Children [also of type Post, where Post.parent_id == foreignKey]:
        var $hasMany = array( 'Child' => array(            
            'className' => 'Post',
            'foreignKey' => 'parent_id',
            'conditions' => array( "Child.active" => "1" )    
        );

        var $belongsTo = array(
            'User' => array(
            'className' => 'User',
            'foreignKey' => 'dom',
            'fields' => array( "User.id" , "User.firs开发者_Go百科t_name" , "User.last_name" )
        )
    );

    }
?>

And a post_controller like this:

<?php
    class PostsController extends AppController {
        var $helpers = array ('Html','Form');
        var $name = 'Posts';

        function index() {
            $conditions = array( "Post.parent_id" => "0" , "Post.active" => "1" );
                $this->set(     'posts', $this->Post->find('all',array(  'conditions'=>$conditions   ))   );
                debug(   $this->Post->find('all',array(   'conditions'=>$conditions    )    )   );
    }
    }

?>

And I want all posts to be dumped to the screen. A Post consists of 1 Post, and possibly multiple Child Posts, which are just Posts with a matching Post.parent_id.

I need User information (Users.first_name and Users.last_name etc) to accompany each Post AND each Child Post in the Posts View so that I may echo each Post and its children along with the name of the poster.

QUESTION:

Is there a way to achieve this?

Thanks for any help guys....


You have to retrieve data from your related objects: i.g: to find the User who created a Post (in your posts controller): (give $user_id the correct value, then:) And then set the variable so the view can use it:

$post = $this->Post->User->findById($user_id);
$this->set('viewVariable', $post);

Using debug($this->Post->User->findByWhateveryouwant); I think you will get by : )

0

精彩评论

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