phalcon / cphalcon

High performance, full-stack PHP framework delivered as a C extension.
https://phalcon.io
BSD 3-Clause "New" or "Revised" License
10.79k stars 1.96k forks source link

[NFR] Named scopes in Models #1502

Closed iforp closed 7 years ago

iforp commented 11 years ago

There is a great feature in Yii framework called Named Scopes. // The original idea of named scopes came from Ruby on Rails.

It is like query builder, but more usable 'cause of custom conditions set. Check it out:

// This is Post model class
class Post extends CActiveRecord
{
    // through "scopes" method, which will be used with magic __call method
    public function scopes()
    {
        return array(
            'published' => array(
                'condition' => 'status=1',
            )
        );
    }

    // through named method with additional params
    public function recently($limit = 5)
    {
        $this->getDbCriteria()->mergeWith(array(
            'order' => 'create_time DESC',
            'limit' => $limit,
        ));
        return $this;
    }

    // this is default scope that would be applied for all queries (including relational ones) 
    public function defaultScope()
    {
        return array(
            'condition'=>"language='en'",
        );
    }
}

// now I can find records with named conditions
$posts = Post::model()
    ->published()  // only posts with status=1
    ->recently(10) // SORT BY create_time DESC and LIMIT 10
    ->findAll();

Also through scope you can join other models. Really miss this functionality in Phalcon.

This issue may be similar to #926

le51 commented 11 years ago

see also on forum here: http://forum.phalconphp.com/discussion/286/named-scopes

kpitn commented 10 years ago

+1 it's a must have feature

sergeyklay commented 7 years ago

I want to close this issue because I don't want a bunch of these lying around. I'd like to add support for anything/everything at some point, but keeping the issue open doesn't help that. :) If anyone wants to get started, I'd love that.