Skip to content

Rails 3 style finder method chaining and scopes #145

Open
@ejunker

Description

@ejunker

I think it would be nice if I could do a query like this:

Book::where('price < ?', 15.00)->all();

instead of the current verbose version:

Book::all(array('conditions' => array('price < ?', 15.00)));

Though due to implementation I realize the syntax may have to be something like:

Book::query()->where('price < ?', 15.00)->all();

query() would return an object which keeps track of the where conditions. where() would return $this so more methods could be chained on to it. When all() is called it uses the stored conditions in the query object to generate the SQL and execute the query.

I think something like this could also be used to create something similar to Rails' scopes. Just create a function that sets the proper where conditions. Perhaps something like this:

public static function cheapBooks()
{
   return static::query()->where('price < ?', 15.00);
}

Then to use it I could just call:

Book::cheapBooks()->all();
// chaining on an order by clause
Book::cheapBooks()->order("price")->all();

You may want to take a look at how rapide-activerecord does this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions