0

I have 2 model: Product and SellingProduct. SellingProduct store selling information as sold date, sold price. A product record has many selling product records.

I want to fetch latest selling product record of a product. I use hasOne but don't work.

$this->hasOne('LastSellingProduct', [
        'foreignKey' => 'product_id',
        'order' => ['LastSellingProduct.created' => 'DESC'],
        'limit' => 1,
        'propertyName' => 'last_selling_product',
        'className' => 'SellingProducts'
    ]);

Please help me!

dario
  • 5,149
  • 12
  • 28
  • 32
  • possible duplicate of [Loading Associated Model Data in Cakephp3](http://stackoverflow.com/questions/30241975/loading-associated-model-data-in-cakephp3) – ndm May 23 '15 at 13:43

1 Answers1

0

How about using virtual fields instead?

I would set

$this->virtualFields('LastSellingProduct','SELECT product_id from `selling_products` where id = (SELECT MAX(id) from `selling_products` WHERE product_id=Product.id)');

or from your products Model add a virtual field

public $virtualFields = array('LastSellingProduct'=>'(SELECT product_id FROM `selling_products` WHERE id = (SELECT MAX(id) FROM `selling_products` WHERE product_id=Product.id))');