开发者

symfony - mysql to Criteria()

I have the following in mySQL:

SELECT t.tag, COUNT( * ) AS `c开发者_如何学Goount`
FROM tag t, content_item_tag c
WHERE t.id = c.tag_id
GROUP BY t.id, c.tag_id
ORDER BY count DESC
LIMIT 0 , 30

Can someone help me convert this to a Criteria() query in Propel?

Thanks


See the latest entry on Propel's blog: How Can I Write This Query Using An ORM? The following is a quote from there:

Answer #1: You Don’t Need An ORM

A recent post on the propel-users mailing list asked for the Propel version of the following query:

SELECT COUNT(t1.user) AS users, t1.choice AS lft, t2.choice AS rgt
FROM Choices t1 iNNER JOIN Choices t2 ON (t1.user = t2.user)
WHERE t1.choice IN (...) AND t2.choice IN (...)
GROUP BY t1.choice, t2.choice;

This query is not object-oriented, it’s purely relational, so it doesn’t need an Object-Relational Mapping. The best way to execute this query inside an ORM is to skip the ORM and use PDO directly:

<?php
$con = Propel::getConnection();
$query = 'SELECT COUNT(t1.user) AS users, t1.choice AS lft, t2.choice AS rgt
  FROM choice t1 iNNER JOIN choice t2 ON (t1.user = t2.user)
  WHERE t1.choice IN (?, ?) AND t2.choice IN (?, ?)
  GROUP BY t1.choice, t2.choice';
$stmt = $con->prepare($query);
$stmt->bindValue(1, 'foo');
$stmt->bindValue(2, 'bar');
$stmt->bindValue(3, 'baz');
$stmt->bindValue(4, 'foz');
$res = $stmt->execute();

Hints of a purely relational query are:

  • The SELECT part cherry-picks some columns of the main table
  • The SELECT part aggregates data from several tables
  • The selected columns use vendor-specific SQL functions
  • The query joins tables through columns that don’t share a foreign key
  • The query is long and makes several joins
  • The query uses GROUP BY or HAVING
  • The user posts the query, but has no idea of the corresponding object model

That’s the most common answer to the “How Can I Write…” question. It is not a bad thing to resort to a direct database query inside a project using an ORM when it’s the right tool for the job. If Propel makes the code much more complex to write, not reusable, or painfully slow, then don’t use it. Be pragmatic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜