Finding Beans

From RedBean

Jump to: navigation, search

Finding Beans

The easiest way to search a bean using RedBean is to use the Find plugin. This plugin is enabled by default; works for most databases and accepts plain old SQL. Here is an example:

$actors = Finder::where("page", " name LIKE :str ", array(":str"=>'%more%'));

The first argument should be the type of bean you are looking for. The second argument is the WHERE-clause. The third argument is an array with slot-value pairs to be inserted in the SQL template provided in the second argument. You should write this where clause as if you were writing it in a plain SQL query. Finder::where is nothing more than a convenience function; it prefixes your SQL with a simple SELECT FROM SQL snippet and fetches the the properties. Afterwards; if the query has any results it converts the records to beans for you.

Search API

This is where most ORM layers simply get it wrong. An ORM tool is only useful if you are doing object relational tasks. Searching a database has never been a strong feature of objects; but SQL is simply made for the job. In many ORM tools you will find statements like: $person->select("name")->where("age","20") or something like that. I found this a pain to work with. Some tools even promote their own version of SQL. To me this sounds incredibly stupid. Why should you use a system less powerful than the existing one? This is the reason that RedBean simply uses SQL as its search API.

Selecting Beans from the database

To search for specific beans in your database; we use a two-step system. First we select the IDs we want to fetch; then we let RedBean convert these to the appropriate beans. For instance, if we are looking for all pages that contain the name John we write:

$keys = $adapter->getCol("SELECT id FROM page WHERE `name` LIKE '%John%'");

Okay now we have a list of primary key IDs from the database. We can do anything with this list: chop it up for pagination; change the order etc. To convert them to beans we simply use the batch loader from the RedBean Core Class:

$pages = $redbean->batch("page", $keys);
Personal tools