Skip to content

Composite Primary Key

Richard edited this page Jun 16, 2016 · 1 revision

Composite Primary Keys

Maphper allows composite primary keys. For example, if you had a table of products you could use the manufacturer id and manufacturer part number as primary keys (Two manufacuterers may use the same part number)

To do this, define the data source with an array for the primary key:

$pdo = new PDO('mysql:dbname=maphpertest;host=127.0.0.1', 'username', 'password');
$productSource = new \Maphper\DataSource\Database($pdo, 'products', ['manufacturerId', 'partNumber']);
$products = new \Maphper\Maphper($productSource);

Once you have defined the source to use multiple keys, you can treat the $products variable like a two dimensional array:

//Get the product with manufacturerId 7 and partNumber AC294
echo $products[7]['AC294']->name;

To write data using composite keys, you simply write an object to a specified index:

$pdo = new PDO('mysql:dbname=maphpertest;host=127.0.0.1', 'username', 'password');
$productSource = new \Maphper\DataSource\Database($pdo, 'products', ['manufacturerId', 'partNumber']);
$products = new \Maphper\Maphper($productSource);

$product = new stdClass;
$product->name 'Can of cola';

$products[1]['CANCOLA'] = $product;