Skip to content

Instantly share code, notes, and snippets.

@manuweg
Created June 29, 2017 07:27
Show Gist options
  • Save manuweg/4e94e477db68df19d71c3a82d21e288b to your computer and use it in GitHub Desktop.
Save manuweg/4e94e477db68df19d71c3a82d21e288b to your computer and use it in GitHub Desktop.
OrderItemsTable.php
<?php
namespace Shop\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Shop\Model\Entity\OrderItem;
/**
* OrderItems Model
*
* @property \Cake\ORM\Association\BelongsTo $Orders
* @property \Cake\ORM\Association\BelongsTo $Products
*/
class OrderItemsTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
*
* @return void
*/
public function initialize(array $config)
{
$this->table('shop_order_items');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Orders', [
'foreignKey' => 'order_id',
'joinType' => 'INNER',
'className' => 'Shop.Orders'
]);
$this->belongsTo('Products', [
'foreignKey' => 'product_id',
'joinType' => 'INNER',
'className' => 'Shop.Products'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
*
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'integer'])
->allowEmpty('id', 'create');
$validator
->add('quantity', 'valid', ['rule' => 'integer'])
->requirePresence('quantity', 'create')
->notEmpty('quantity');
$validator
->add('price', 'valid', ['rule' => 'numeric'])
->requirePresence('price', 'create')
->notEmpty('price');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
*
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['order_id'], 'Orders'));
$rules->add($rules->existsIn(['product_id'], 'Products'));
return $rules;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment