我只是尝试用户拥有多个帖子的hasMany关系中最简单的示例。保存帖子进行测试时,user_id在视图代码中是硬连线的。
问题:
假设$ users从帖子中返回了已加入的数据,$ user->会发布正确的访问方式吗?
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; ?>