Why does doctrine (1.2) use WHERE IN
instead of LIMIT
?
This code:
Doctrine_Query::create()
->from('Table t')
->limit(10)
->g开发者_如何转开发etSqlQuery();
Returns something like this:
SELECT t.id_table AS t__id_table FROM table AS t WHERE t__id_table IN (1,2,3,4,10,12,18,20,21,25);
Instead of this:
SELECT t.id_table AS t__id_table FROM table AS t LIMIT 10;
This behaivor is same for any LIMIT
value. This generates a very long queries for high LIMIT
values.
Bonus question: How does Doctrine know, what ids to use? (By sending another query to DB??)
That's because LIMIT
operates on database rows not "objects". When you type $q->limit(10)
you want to get ten objects, not ten rows from database.
Consider following query (products and categories have many-to-many relationship):
SELECT p.*, c.* FROM product p
INNER JOIN product_category_ref pcr ON p.id = pcr.prodcut_id
INNER JOIN category c ON c.id = pcr.category_id
WHERE p.price < 123;
To fetch 10 products (objects) your query will have to fetch at least 20 rows. You cannot use LIMIT 10
cause (just for example) only 3 products would be returned. That's why you need to find out which products should be fetched (limit applies to products), and later fetch the actual data.
That will result in following queries:
SELECT p.id FROM product p WHERE p.price < 123;
SELECT ..... WHERE p.id IN (...);
Second query might return 20, 423 or 31 rows. As you can see that's not a value from limit()
.
PS. Doctrine2 is much more clearer in that case as it's using setMaxResults()
method instead of limit()
which is less confusing.
Using Doctrine 1.2.3:
<?php
include(dirname(__FILE__).'/Doctrine.php');
spl_autoload_register(array('Doctrine', 'autoload'));
$dbh = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'testdb', 'testdb');
$conn = Doctrine_Manager::connection($dbh);
class Table extends Doctrine_Record {
public function setTableDefinition() {
$this->hasColumn('id_table', integer, 10, array('primary' => true));
}
}
$q = Doctrine_Query::create()
->from('Table t')
->limit(10)
->getSqlQuery();
echo $q;
I get the result:
SELECT t.id_table AS t__id_table FROM table t LIMIT 10
Is there maybe something else going on in your code?
精彩评论