RedBeanPHP Cheat Sheet

From PaskvilWiki
Revision as of 00:18, 10 January 2016 by Admin (Talk | contribs)

Jump to: navigation, search

RedBeanPHP site

I love RBPHP since it's single file light-weight x-DB and clean ORM. -- my opinion (R) --

This is by no means complete cheat sheet; many things were left out, see full documentation for all tips and tricks.

Basics and CRUD

Download RedBeanPHP

require 'rb.php';
R::setup();

// create a new bean, and setting some properties (member and array access supported);
// the bean name has to be lowercase alphabetical;
// properties names have to contain only alphanumeric and underscore
$book = R::dispense('book');
$book->title = 'Learn to Program';
$book['rating'] = 10;
$book['price'] = 29.99;

// save it - if table does not exist, RBPHP will create it based on added properties;
// if it does exist, RBPHP will update the table to hold any new data, if necessary
$id = R::store($book);

// reading a bean by ID, or multiple by array of ID's
$book = R::load('book', $id);
$books = R::loadAll('book', $ids);

// updating a bean
$book->title = 'Learn to fly';
$book->rating = 'good';             // rating will be changed from integer to varchar
$book->published = '2015-02-15';    // column will be added, type 'date'; R::isoDate() and R::isoDateTime() generate current date(time)
R::store($book);

// deleting a bean or multiple beans
R::trash($book);
R::trashAll($books);

// delete all beans of given type
R::wipe('book');

// destroy the whole DB
R::nuke();

// reload bean from DB
$bean = $bean->fresh();

Select / Query

$book = R::find('book', 'rating > 4');
$books = R::find('book', 'title LIKE ?', ['Learn to%']);    // with bindings
$promotions = R::find('person', 'contract_id IN ('.R::genSlots($contractIDs).')', $contractIDs);    // R::genSlots() generates ?'s for bindings
$book = R::findOne('book', 'title = ?', ['SQL Dreams']);    // returns single bean, not array; NULL if none found

// find all, no WHERE's
$books = R::findAll('book');
$books = R::findAll('book' , 'ORDER BY title DESC LIMIT 10');

// all of find(), findOne(), and findAll() support named slots
$books = R::find('book', 'rating < :rating', [':rating' => 2]);

// using cursors - saves on loading
$collection = R::findCollection('page', 'ORDER BY content ASC LIMIT 5');
while($item = $collection->next())
    // process bean $item

// find with multiple possible values
R::findLike('flower', ['color' => ['yellow', 'blue']], 'ORDER BY color ASC');

// if the bean does not exist, it's created
$book = R::findOrCreate('book', ['title' => 'my book', 'price' => 50]);