WordPress has all sorts of functions for saving and retrieving your data from the 12 database tables it already knows, but since we now can easily create new database tables with Database Migrations, we need a new way of fetching your data.
In Cuisine we do this with the Record class, which is available through Cuisine’s wrapper system. Just include the following namespace:
use Cuisine\Wrappers\Record
$id = '1';
Record::get( 'product_meta', $id );
We tell the record class to go and fetch the product_meta with an ID of 1. This will return a stdObject with your data.
If you want to look for a record that you don’t know the ID of, you can use the find
method, which we’ll also use to fetch multiple records in later examples. For now, here’s how you get a single record:
$productId = '1';
Record::find( 'product_meta' )->where( 'product_id', $productId )->first();
As you can see all of these methods are chainable, which makes this query very easy to read. This will return the first record it finds where the product_id is equal to $productId.
$meta = Record::find( 'product_meta' )
->where(['product_id' => $product_id ])
->results();
$metaArray = $meta->toArray();
In this example we’ll get all records in the product_meta table that belong to our $product_id variable. The results will be a Cuisine Collection, which you can easily convert to an array, a json string or whatever you fancy.
You may have noticed that the where method takes an array as it’s parameter. In this array we can of course put multiple clauses. Like so:
Record::find( 'product_meta' )
->where([
'product_id' => $product_id,
'price' => 0
])->results();
This example will return a collection of product meta where the price is zero.
Important to know: Adding WHERE clauses results in “AND” queries by default. Currently we’re still working on “OR” support.
Record::find()
queries will return either anArray
ornull
if the query returned no table rows.