1

User hasMany Posts の hasMany リレーションの最も単純な例を試しています。user_id は、テスト用に投稿を保存するときにビュー コードに組み込まれています。

質問:

  1. リレーションシップは、ドキュメント データベース/mongodb の Lithium 0.11 リリースでサポートされていますか?
  2. コントローラーはユーザーに属する投稿を返すことが期待されていますが、何も返されません
  3. $users が投稿から結合されたデータを返したと仮定すると、$user->posts はそれにアクセスする正しい方法ですか?

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

0 に答える 0