Doctrine ORM - 没有任何真实关系的自我加入

时间:2010-01-27 10:08:15

标签: sql mysql symfony1 doctrine dql

我试图通过匹配对象标签来找到一个对象的相关对象。我构建了一个mysql查询,通过计算匹配的标记返回最匹配的对象。

我是学说(1.2)的新手,所以我想知道是否有人可以帮助我在正确的轨道上修改我的架构并创建DQL查询?最大的问题是我的schema.yml中两个tagset与彼此没有关系。我猜。

的schema.yml:

Object:
  columns:
    name:
  relations:
    Tags: { foreignAlias: Objects, class: Tag, refClass: Tagset}

Tagset:
  columns:
    object_id: {type: integer, primary: true, notnull: true}
    tag_id: { type: integer, primary: true, notnull: true }
  relations:
    Object: { foreignAlias: Tagsets }
    Tag: { foreignAlias: Tagsets }

Tag:
  columns:
    name: { type: string(255), notnull: true }
    Object: { foreignAlias: Tags, class: Object, refClass: Tagset}

以下是使用上述模式的mysql查询:

SELECT object.name, COUNT(*) AS tag_count
FROM tagset T1
INNER JOIN tagset T2
    ON T1.tag_id = T2.tag_id AND T1.object_id != T2.object_id
INNER JOIN object
    ON T2.object_id = object.id
WHERE T1.object_id = 2
GROUP BY T2.object_id
ORDER BY COUNT(*) DESC

2 个答案:

答案 0 :(得分:2)

您也可以使用子查询。像这样:

$object_id = 2;

Doctrine::getTable('Tagset')->createQuery('t')
  ->select('t.tag_id, o.id, o.name, COUNT(t.tag_id) AS tag_count')
  ->innerJoin('t.Object o WITH o.id != ?', $object_id)
  ->where('t.tag_id IN (SELECT t.tag_id FROM Tagset t WHERE t.object_id = ?)', $object_id)
  ->groupBy('t.object_id')

答案 1 :(得分:1)

解决方案:

$q = new Doctrine_RawSql();
    $this->related_objects = $q->
            select('{o.name}')->
            from('tagset t1 JOIN tagset t2 ON t1.tag_id = t2.tag_id AND t1.object_id != t2.object_id JOIN object o ON t2.object_id = o.id')->
            addComponent('o','Object o')->
            where('t1.object_id = ?', $this->object->id)->
            groupBy('t2.object_id')->
            orderBy('COUNT(*) DESC')->
            execute();