2012-06-06 1 views
0

사용자, 범주 및 게시물이 있습니다. 사용자는 여러 개의 게시물을 가지고 있으며, 카테고리는 많은 게시물을 가지고 있으며, 게시물은 하나의 카테고리와 하나의 사용자에 속합니다.Kohana ORM 피벗 테이블 잘못된 데이터

올바른 사용자에게 올바른 게시물을 표시하는 데 도움이 필요합니다.

테이블

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; 

카테고리 및 게시물하지만 사용자하지 않습니다.

user_id post_id 
1  1 
1  2 
1  3 
2  4  

위의 코드는 메아리 사용 하나, 사용자 두, NULL 대신 사용 하나, 사용자 하나, 사용자 하나, 사용자 두의 NULL :

는 다음있다 users_posts 말할 수 있습니다. 어떤 이유에서 Post 1은 User 1과 Post 2는 User 2와 일치합니다. ID 번호가 같기 때문입니다.

내가 뭘 잘못하고 있니?

Category One 
Post One 
User One 
Post Two 
User Two 

Category Two 
Post Three 
NULL 
Post Four 
NULL 

답변

0

당신은 정말 당신이 많은-에 추적 할 필요가있을 때 피벗 테이블을 사용해야합니다

여기
Category One 
Post One 
User One 
Post Two 
User One 

Category Two 
Post Three 
User One 
Post Four 
User Two 

코드 에코는 무엇인가 : 다음

는 에코 무엇을 생각입니다 이 시나리오에서는 추적 할 일대 다 관계가 없습니다 (일대 다 관계).

처음에는 Post 모델에 외래 키로 user_idcategory_id 필드가 있어야 일대 다 관계를 추적 할 수 있습니다. 문서는 사용자, 카테고리, 게시물 예제 (달성하고자하는 것과 거의 동일)를 사용하여 모델을 구성하는 방법을 설명합니다. http://kohanaframework.org/3.2/guide/orm/relationships

+0

감사합니다. 조언 해 주셔서 감사합니다. – markerpower