Respect / Relational

A fluent, intuitive ORM for any relational database engine
http://respect.github.io/Relational
Other
243 stars 32 forks source link

SQL SERVER TOP (LIMIT) #81

Closed ricardofontanelli closed 8 years ago

ricardofontanelli commented 8 years ago

I need to build a query using the TOP argument (it's like MySql LIMIT XX) in a legacy database. Does anybody have some idea how can I build it using Mapper? By default the query is like that: SELECT TOP 10 * FROM [TABLE].

alganet commented 8 years ago

Doing that on the Mapper is possible, but it requires you to extend an internal class. I can help you if you need that.

Often people prefer to use the Db class directly in order to use non-standard queries:

use Respect\Relational\Db;
// Setting up
$db = new Db(new Pdo( /* your own PDO settings here */ ));

$limit = 10;
// Syntax Alternative 1
$db->selectTop10('*')->from('comment')->fetchAll();
// Syntax Alternative 2
$db->selectTop($limit, '*')->from('comment')->fetchAll();
// Syntax Alternative 3
$db->{'selectTop' . $limit}('*')->from('comment')->fetchAll();

I've made three samples because I'm not sure which one would work, perhaps all of them. That is because the Db and Sql classes are domain specific language builders (they translate method calls to SQL syntax without parsing the entire grammar).

Let me know if none of these samples work or if you really need them in the Mapper class, I'll help you out.

ricardofontanelli commented 8 years ago

Perfect, it’s just what I need! The second alternative needs a small adjust:

// Syntax Alternative 2
$db->selectTop("$limit *")->from('comment')->fetchAll();

Thanks a lot, Db class is very powerfull!