您必须在 prestashop 中创建 Product 类的覆盖。为此,请在 override/classes 中创建一个名为 Product.php 的新文件并将此代码放入其中:
<?php
class Product extends ProductCore
{
// Here we will put every method or property override
}
在本课程中,您将复制/粘贴静态方法priceCalculation(对我来说它位于原始 Product.php 文件的第 2567 行)。完成后,只需在方法末尾添加这些行,就在 self::$_prices[$cache_id] = $price; 之前:
if ($id_product == 44 && Context::getContext()->customer->isLogged()) {
$customer = Context::getContext()->customer;
$nbTimesBoughtThisProduct = (int) Db::getInstance()->getValue('
SELECT COUNT(*)
FROM `' . _DB_PREFIX_ . 'product` p
JOIN `' . _DB_PREFIX_ . 'order_detail` od
ON p.`id_product` = od.`product_id`
JOIN `' . _DB_PREFIX_ . 'orders` o
ON od.`id_order` = o.`id_order`
WHERE o.`id_customer` = ' . $customer->id . '
AND p.`id_product` = ' . $id_product . '
');
$price += $nbTimesBoughtThisProduct * 10;
}
我没有时间测试这些,但我认为这是做你想做的事情的方法。
priceCalculation 是每次 Prestashop 需要产品价格时调用的方法。通过将此代码放在该方法的末尾,我们修改了返回的价格。
代码首先检查客户是否已登录(如果他未登录,我们将无法从他那里获得订单)。如果是这样,查询会检索该客户过去购买此产品的次数。这个数字乘以 10,然后价值被添加到价格中。
编辑:如果正如 Cyril Tourist 所说,您还想计算当前购物车,请获取此新代码(尚未测试,但应该可以使用):
if ($id_product == 44 && Context::getContext()->customer->isLogged()) {
$customer = Context::getContext()->customer;
$nbTimesBoughtThisProduct = (int) Db::getInstance()->getValue('
SELECT COUNT(*)
FROM `' . _DB_PREFIX_ . 'product` p
JOIN `' . _DB_PREFIX_ . 'order_detail` od
ON p.`id_product` = od.`product_id`
JOIN `' . _DB_PREFIX_ . 'orders` o
ON od.`id_order` = o.`id_order`
WHERE o.`id_customer` = ' . $customer->id . '
AND p.`id_product` = ' . $id_product . '
');
$productsInCart = Context::getContext()->cart->getProducts();
foreach ($productsInCart as $productInCart) {
if ($productInCart['id_product'] == 44) {
$nbTimesBoughtThisProduct++;
}
}
$price += $nbTimesBoughtThisProduct * 10;
}
另外,我建议您将“44”产品 ID 存储在常量、配置变量或任何内容中,但不要将其保存在这样的代码中。我这样做只是为了示例。