This is the documentation for LemonStand V1, which has been discontinued. You can learn more and upgrade your store here.

LemonStand Version 1 Has Been Discontinued

This documentation is for LemonStand Version 1. LemonStand is now offered as a cloud-based eCommerce platform.
You can try the new LemonStand and learn about upgrading here.

Extending Models with Related Columns

In some circumstances you may need to extend an existing model with a related column. For example, if you sell software, you may want to add the "Media type" field to your products. The list of media types can be a separate table, and products should have a foreign key referring to the primary key in the media types table.

As this type of relation is a Belongs To relation, you need to create a foreign key in the products table. Data relations are described in the Creating data relations article. Please also read the Extending existing models article to learn how you can add a new field to the shop_products table.

A data model class should be defined for the related table, in this case for the media types. Please read the Working with the database article for details about creating model classes.

At last, when you have a foreign key field in the products table, and a model class for the related table, you can extend the product model in the following way:

public function subscribeEvents()
{
    Backend::$events->addEvent('shop:onExtendProductForm', $this, 'extend_product_form');
    Backend::$events->addEvent('shop:onExtendProductModel', $this, 'extend_product_model');
}

/*
 * Event handlers
 */

public function extend_product_model($product)
{
    $product->add_relation('belongs_to', 'media_type', array('class_name'=>'MyModule_MediaType', 'foreign_key'=>'x_media_type'));
    $product->define_relation_column('media_type', 'media_type', 'Media Type ', db_varchar, '@name');
}

public function extend_product_form($product)
{
    $product->add_form_field('media_type')->tab('My Tab');
}

The add_relation() method adds data relations in the same way as it is described in the Creating data relations article. Alternatively you can define has-many relations. In this case you will need to define a join table instead of the foreign key.


Previous: Extending Existing Models
Return to Extending Existing Models