2010-10-05 85 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