Question

How to add custom field in product collection? I want to add discount value field in product collection.

When I print product collection, it's output like this :

[0] => Array
        (
            [entity_id] => 1
            [attribute_set_id] => 15
            [type_id] => simple
            [sku] => 24-MB01
            [has_options] => 0
            [required_options] => 0
            [created_at] => 2021-01-27 09:13:37
            [updated_at] => 2021-03-30 15:01:25
            [cat_index_position] => 0
            [price] => 40.000000
            [tax_class_id] => 0
            [final_price] => 16.000000
            [minimal_price] => 16.000000
            [min_price] => 16.000000
            [max_price] => 16.000000
            [tier_price] => 
        )

I want like this :

[0] => Array
        (
            [entity_id] => 1
            [attribute_set_id] => 15
            [type_id] => simple
            [sku] => 24-MB01
            [has_options] => 0
            [required_options] => 0
            [created_at] => 2021-01-27 09:13:37
            [updated_at] => 2021-03-30 15:01:25
            [cat_index_position] => 0
            [price] => 40.000000
            [tax_class_id] => 0
            [final_price] => 16.000000
            [minimal_price] => 16.000000
            [min_price] => 16.000000
            [max_price] => 16.000000
            [tier_price] => 
            [discount_value] => 60.00000
        )

How can I add that field?

Please help me.

Was it helpful?

Solution

Use this code after your collection :

$collection->getSelect()->columns(
    ['discount_value' => new \Zend_Db_Expr('ROUND(((price - final_price) / price) * 100,2)')]
);

You will get same result as you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top