我只是尝试用户拥有多个帖子的hasMany关系中最简单的例子 . 保存用于测试的帖子时,user_id在视图代码中是硬连线的 .

问题:

  • 文档数据库/ mongodb的Lithium 0.11版本是否支持关系?

  • 控制器应返回属于该用户的帖子,但不返回任何内容

  • 假设$ users从帖子中返回了已加入的数据,$ user-> post是否有正确的访问方式?

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');
}

模型类:

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

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

}

索引视图用于打印帖子以及包含属于它们的帖子的用户 .

<?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; ?>