2010-03-01 113 views
2

在我的代碼有三個類,如下所示:ForumForum::ThreadForum::Post如何使用DBIx :: Class創建嵌套的has_many或belongs_to關係?

我想要做的就是創建一個從Forum::Post類的Forum類,反之亦然用的has_many一個belongs_to的關係,最好而無需爲其創建自定義功能。 (這當然是更多的智力練習,而不是技術限制或實際問題,但如果可能的話,我很想知道。)

註釋掉的行包含我關於關係的意圖,但是在它們的當前形式,他們失敗了。我在文檔中探索過,但找不到與此特定案例相關的任何內容。

任何指針?

論壇等級:

package Schema::Result::Forum; 

use Moose; 
extends qw/DBIx::Class/; 

__PACKAGE__->load_components (qw/Core/); 
__PACKAGE__->table ('forum'); 

__PACKAGE__->add_columns (
    id => { 
    is_auto_increment => 1, 
    data_type   => 'integer', 
    }, 
); 

__PACKAGE__->set_primary_key ('id'); 

__PACKAGE__->has_many (threads => 'Schema::Result::Forum::Thread'); 
#This is the interesting line 
#__PACKAGE__->has_many (posts => 'threads' => 'forums'); 

1; 

Thread類:

package Schema::Result::Forum::Thread; 

use Moose; 
extends qw/DBIx::Class/; 

__PACKAGE__->load_components (qw/Core/); 
__PACKAGE__->table ('forum_thread'); 
__PACKAGE__->add_columns (
    id => { 
    is_auto_increment => 1, 
    data_type   => 'integer', 
    }, 
    forum => { 
    data_type   => 'integer', 
    }, 
); 

__PACKAGE__->set_primary_key ('id'); 

__PACKAGE__->belongs_to (forum => 'Schema::Result::Forum'); 
__PACKAGE__->has_many (posts => 'Schema::Result::Forum::Post'); 

1; 

Post類:

package Schema::Result::Forum::Post; 

use Moose; 

extends qw/DBIx::Class/; 

__PACKAGE__->load_components (qw/Core/); 

__PACKAGE__->table ('forum_post'); 

__PACKAGE__->add_columns (
    id => { 
    is_auto_increment => 1, 
    data_type   => 'integer', 
    }, 
    thread => { 
    data_type   => 'integer', 
    }, 
); 

__PACKAGE__->set_primary_key ('id'); 

__PACKAGE__->belongs_to (thread => 'Schema::Result::Forum::Thread'); 
#This is the other interesting line 
#__PACKAGE__->belongs_to (forum => 'thread' => 'forum'); 

1; 

PS:附加列,持有的實際內容進行了省略簡潔。

+0

你有什麼期望這個嵌套關係呢?在這些情況下'$ post-> forum'或$ forum-> post'是什麼意思?你不能只使用'$ post-> thread-> forum'和'爲我的$ thread($ forum-> threads){爲我的$ post($ thread-> posts){}}'做你想做的事? – 2010-03-03 17:59:04

+0

@Phillip Potter:我有點擔心過期;我最終想用'$ forum-> posts'實現的是*一個* SQL查詢,它提取所有數據。 $ post-> forum實際上只是$ post-> thread-> forum的簡寫,所以我認爲這不太有趣。 – 2010-03-04 12:17:25

+0

我建議你訂閱DBIx :: Class郵件列表並在那裏詢問。我不確定如何去做你所要求的。 – 2010-03-07 07:58:46

回答

1

它看起來像嵌套關係是不可能的。 has_many接受一個外部類,它具有調用類的外鍵。

好消息是$forum->threads->posts返回單個DBIx::Class::Resultset。它在需要之前不會被翻譯成SQL,因此當您撥打$forum->threads->posts->all()或甚至像$forum->search_related('threads',{},{rows=>25})->posts->all()這樣的內容時,它只會運行一個查詢。

如果你的目標是有一個$後>的論壇,它可以永遠是一個方法:sub forum{$_[0]->thread->forum}

0

您使用的是什麼數據庫和引擎類型?如果你沒有外鍵(比如在MySQL中使用myisam表),那麼你必須在關係語句中提供列名。

相關問題