2010-10-05 62 views
0

我正在做一個使用symfony作爲學習練習的博客引擎。如何訪問鏈接到博客文章的標籤列表?

如何從博客文章的ID中獲取標籤列表? 這裏的數據庫瑪: alt text

我加在模型如下:

public static function getTags($id) 
{ 
    return Doctrine_Core::getTable('Tag') 
    ->createQuery('t') 
    ->select('t.name, t.slug') 
    ->leftJoin('t.ContentTag ct') 
    ->where('ct.content_id = ?', $id) 
    ->orderBy('t.name ASC'); 

} 

這裏是schema.yml中的一部分:

Content: 
    connection: doctrine 
    tableName: ec_content 
    actAs: 
    Sluggable: 
     fields: [title] 
     unique: true 
     canUpdate: true 
    Timestampable: 
    columns: 
    id: 
     type: integer(4) 
     fixed: false 
     unsigned: true 
     primary: true 
     autoincrement: true 
(...) 
    relations: 
    Comment: 
     local: id 
     foreign: content_id 
     type: many 
    ContentTag: 
     local: id 
     foreign: content_id 
     type: many 

ContentTag: 
    connection: doctrine 
    tableName: ec_content_tag 
    columns: 
    content_id: 
     type: integer(4) 
     fixed: false 
     unsigned: true 
     primary: true 
     autoincrement: false 
    tag_id: 
     type: integer(4) 
     fixed: false 
     unsigned: true 
     primary: true 
     autoincrement: false 
    relations: 
    Content: 
     local: content_id 
     foreign: id 
     type: one 
    Tag: 
     local: tag_id 
     foreign: id 
     type: one 

回答

1

這很難說沒有看到確切地說你的模式是如何定義的(即schema.yml),但是我的猜測是,假設你已經加載了content對象,那麼這是可行的:

$tags = $content->Tags; 

否則,你的代碼片段應該工作,據我所知。你只需要在堅持到底->exec(),使其返回查詢的結果,而不是查詢對象本身:

return Doctrine_Core::getTable('Tag') 
    ->createQuery('t') 
    ->select('t.name, t.slug') 
    ->leftJoin('t.ContentTag ct') 
    ->where('ct.content_id = ?', $id) 
    ->orderBy('t.name ASC') 
    ->exec(); 

編輯在看到您的模式,似乎還沒有創建內容和標籤之間的關係,您需要做的。你可以讓Doctrine處理他們的交互。 Symfony和Doctrine書籍使用與您的示例基本相同的內容來演示how to do a many-to-many relationship。 (請注意,雖然此文檔是針對symfony的過時版本,但此功能的語法並未更改。)

+0

我不知道「refClass」,謝謝! – Manu 2010-10-05 14:47:51