1

I'm just trying out the simplest of the examples for hasMany relations where User hasMany Posts. A user_id is hardwired in view code when saving posts for testing.

Questions:

  1. Are relationships supported for Lithium 0.11 release for document database/mongodb?
  2. The controller is expected to return the posts belonging to the user but none is returned
  3. Assuming $users returned the joined data from posts, is $user->posts the correct way of accessing it?

    class PostsController extends \lithium\action\Controller {      
    public function index() {
    $posts = Posts::find('all', array('with' => 'Users'));        
    $users = Users::find('all',array('with' => 'Posts'));        
    return compact('posts','users');      
    }
    public function add() {
        $success = false;
        if ($this->request->data) {
            $post = Posts::create($this->request->data);
            $success = $post->save();
        }
        return compact('success');
    }
    

The model classes:

    class Posts extends \lithium\data\Model {
    public $belongsTo = array('Users' => array(
                                            'key'=>'user_id'));
}

    class Users extends \lithium\data\Model {
    public $hasMany = array('Posts');

}

The Index View to print out the posts and also the users with the posts belonging to them.

<?php foreach($posts as $post): ?>
<article>
    <h1><?=$post->title ?></h1>
    <p><?=$post->body ?></p>
    <p><?=$post->user_id ?></p>
</article>
<?php endforeach; ?>
<hr/> <hr/>
<?php foreach($users as $user): ?>
<article>
    <h1><?=$user->name ?></h1>
    <p><?=$user->_id ?></p>
    <p><?=$user->posts ?></p>
</article>
<?php endforeach; ?>
Nilesh Kale
  • 233
  • 1
  • 4
  • 12

0 Answers0