我有用户、类别和帖子。用户有很多帖子,类别有很多帖子,帖子属于一个类别和一个用户。
我需要帮助以正确的帖子显示正确的用户。
表
categories{category_id, category_title}
posts{post_id, post_title}
users{user_id, user_title}
categories_posts{category_id, post_id}
users_posts{user_id, post_id}
楷模
class Model_User extends ORM {
protected $_primary_key = 'user_id';
protected $_has_many = array(
'posts'=> array(
'model' => 'post',
'through' => 'users_posts',
'far_key' => 'post_id'
),
);
}
class Model_Category extends ORM {
protected $_primary_key = 'category_id';
protected $_has_many = array(
'posts'=> array(
'model' => 'post',
'through' => 'categories_posts',
'far_key' => 'post_id'
)
);
}
class Model_Post extends ORM {
protected $_primary_key = 'post_id';
protected $_belongs_to = array(
'categories'=> array(
'model' => 'category',
'through' => 'categories_forums',
'far_key' => 'category_id'
),
'users'=> array(
'model' => 'user',
'through' => 'users_posts',
'far_key' => 'user_id'
)
);
}
展示
$categories = ORM::factory('category')->find_all();
foreach ($categories as $category) :
echo $category->category_title;
foreach ($category->posts->find_all() as $post) :
echo $post->post_title;
echo $post->users->user_title;
endforeach;
endforeach;
类别和帖子正确回显,但用户没有。
假设 users_posts 具有以下内容:
user_id post_id
1 1
1 2
1 3
2 4
上面的代码将回显用户一、用户二、NULL、NULL,而不是用户一、用户一、用户一、用户二。由于某种原因,它将帖子一与用户一匹配,将帖子二与用户二匹配,因为它们具有相同的 ID 号。
我究竟做错了什么?
这是假设要回显的内容:
Category One
Post One
User One
Post Two
User One
Category Two
Post Three
User One
Post Four
User Two
这是代码的回声:
Category One
Post One
User One
Post Two
User Two
Category Two
Post Three
NULL
Post Four
NULL