DB.PHP - PHP ORM

Set relation

Relation in orm means that one property of class represents another object of class. For example:

namespace shop
{
    class cart
    {
        public $id;
        /**
        * @var \shop\product
        */
        public $product;
        public function __construct ($product=null)
        {
            $this->product = $product;
        }
    }

    class product
    {
        public $id;
        public $title;
        public function __construct ($title=null)
        {
            $this->title = $title;
        }
    }
}

In this example we have two classes. \shop\cart has property product. @var keyword value of product property can specify which class will represent that property in this case it will represent \shop\product.

So let us create product:

$product = $database->save (new \shop\product('Apple'));

And create cart item with this product:

$cart = new \shop\cart ($product);

If we later load that cart item:

$cart = $database->shop->cart->load (1);

echo $cart->product->title;

It will output Apple

Interested how this 2 records look in table?

Products table:

shop_product
----------------------------
id | title
----------------------------
1  | Apple

Carts table:

shop_cart
----------------------------
id | product
----------------------------
1  | 1

By default related property field type is integer. But if the class you are relating has primary property not integer, for example string then you have to set also type to your related property field:

If we have:

class currency
{
    /**
    * primary
    * length 3
    * @var string
    */
    public $code;
}

And if we want to relate to it we must make related field char(3) as currency id field is:

class cost
{
    public $id;
    /**
    * type char
    * length 3
    * @var currency
    */
    public $currency;
    public $value;
}