korshunov писал(а):Смотрите, как в Okay\Core\Cart.php работает $user = $this->mainHelper->getCurrentUser() и используйте аналогично getCurrentUserGroup().
Попробовал, ничего не выходит(( с объектами в php никогда не работал... например не понимаю что такое $this - от куда мы берем его... Вообще пересмотрел логику своей доработки... Вместо того чтобы добавлять везде вывод оптовой цены и вести расчет используя ее (слишком много файлов менять), я решил сразу подменить поле "price" из таблицы "Variants" для покупателей, которые состоят в группе пользователей с галочкой "показывать оптовую цену". Т.е. в файле /Okay/Entities/VariantsEntity.php в функции "resetInfo" я делаю следующее:
и на всем сайте как и надо сразу подменяются цены из колонки price на колонку price_opt. Но я не знаю теперь как мне сделать так, чтобы эта подмена происходила только для групп покупателей у которых стоит галочка "показывать оптовую цену"...
У меня в бд в таблице с группами есть дополнительная колонка "opt_price" в которой хранится true/false. И мне для создания условия нужно получить значение из колонки "opt_price" группы к которой относится покупатель.
К примеру используя $group-> как в дизайне сайта:
Код: Выделить всё
if($group->opt_price){
$variant->price = $variant->opt_price;
}
Как мне получить эти данные (значение колонки из группы пользователя) для создания подобного условия? Буду очень признателен, мне бы хотя бы один пример, который выполняет мою задачу, по нему я смогу понять как все это работает.... Молю о помощи
Добавлено спустя 6 минут 34 секунды:содержание моего файла /Okay/Entities/VariantsEntity.php
Код: Выделить всё
<?php
namespace Okay\Entities;
use Okay\Core\Entity\Entity;
use Okay\Core\Modules\Extender\ExtenderFacade;
class VariantsEntity extends Entity
{
protected static $fields = [
'id',
'product_id',
'sku',
'weight',
'price',
'opt_price',
'compare_price',
'stock',
'position',
'external_id',
'currency_id',
];
protected static $additionalFields = [
'(v.stock IS NULL) as infinity',
'c.rate_from',
'c.rate_to',
];
protected static $langFields = [
'name',
'units',
];
protected static $defaultOrderFields = [
'position',
'id',
];
protected static $table = '__variants';
protected static $langObject = 'variant';
protected static $langTable = 'variants';
protected static $tableAlias = 'v';
public function get($id)
{
if (empty($id)) {
return ExtenderFacade::execute([static::class, __FUNCTION__], null, func_get_args());
}
$this->select->join('left', '__currencies AS c', 'c.id=v.currency_id');
$variant = parent::get($id);
$variant = $this->resetInfo($variant);
return $variant;
}
public function find(array $filter = [])
{
$this->select->join('left', '__currencies AS c', 'c.id=v.currency_id');
$variants = parent::find($filter);
foreach ($variants as &$variant) {
$variant = $this->resetInfo($variant);
}
return $variants;
}
public function pricesToMainCurrencyByCurrencyId($id)
{
/** @var CurrenciesEntity $currenciesEntity */
$currenciesEntity = $this->entity->get(CurrenciesEntity::class);
$currency = $currenciesEntity->get((int) $id);
$mainCurrency = $currenciesEntity->getMainCurrency();
$mainCurrencyCoef = $this->getMainCurrencyCoef($currency);
$sql = $this->queryFactory->newSqlQuery();
$sql->setStatement("UPDATE ".self::getTable()." SET price=price*{$mainCurrencyCoef}, compare_price=compare_price*{$mainCurrencyCoef}, currency_id=:main_currency_id WHERE currency_id=:currency_id")
->bindValue('currency_id', $id)
->bindValue('main_currency_id', $mainCurrency->id);
$this->db->query($sql);
ExtenderFacade::execute([static::class, __FUNCTION__], null, func_get_args());
}
protected function customOrder($order = null, array $orderFields = [], array $additionalData = [])
{
switch ($order) {
case 'in_stock_first' :
$orderFields = [
'IF(stock=0, 0, 1) DESC',
'position',
'id',
];
break;
}
return ExtenderFacade::execute([static::class, __FUNCTION__], $orderFields, func_get_args());
}
protected function resetInfo($variant)
{
/*Подмена розничной цены на оптовую*/
$variant->price = $variant->opt_price; /*необходимо запихать в условие*/
if (empty($variant)) {
return $variant;
}
if (property_exists($variant, 'compare_price') && $variant->compare_price == 0) {
$variant->compare_price = null;
}
if (property_exists($variant, 'stock') && $variant->stock === null) {
$variant->stock = $this->settings->max_order_amount;
}
if (property_exists($variant, 'units') && $variant->units === null) {
$variant->units = $this->settings->units;
}
return $variant;
}
protected function filter__in_stock()
{
$this->select->where('(v.stock > 0 OR v.stock IS NULL)');
}
protected function filter__not_id($id)
{
$this->select->where("id!=:not_id");
$this->select->bindValue('not_id', (int)$id);
}
protected function filter__has_price()
{
$this->select->where("price > 0");
}
private function getMainCurrencyCoef($currency)
{
return $currency->rate_to / $currency->rate_from;
}
}
Добавлено спустя 1 час 8 минут:Попытался сделать так:
Код: Выделить всё
/*Подмена розничной цены на оптовую*/
if($_SESSION['user_id'] && ($user = $this->usersEntity->get(intval($_SESSION['user_id']))) && $user->opt_price){
$variant->price = $variant->opt_price; /*необходимо запихать в условие*/
}
Выдает ошибку 500...
файл целиком:
Код: Выделить всё
<?php
namespace Okay\Entities;
use Okay\Core\Entity\Entity;
use Okay\Core\Modules\Extender\ExtenderFacade;
use Okay\Entities\UsersEntity;
use Okay\Helpers\MainHelper;
class VariantsEntity extends Entity
{
/** @var UsersEntity */
private $usersEntity;
/** @var MainHelper */
private $mainHelper;
/** @var EntityFactory */
private $entityFactory;
protected static $fields = [
'id',
'product_id',
'sku',
'weight',
'price',
'opt_price',
'compare_price',
'stock',
'position',
'external_id',
'currency_id',
];
protected static $additionalFields = [
'(v.stock IS NULL) as infinity',
'c.rate_from',
'c.rate_to',
];
protected static $langFields = [
'name',
'units',
];
protected static $defaultOrderFields = [
'position',
'id',
];
protected static $table = '__variants';
protected static $langObject = 'variant';
protected static $langTable = 'variants';
protected static $tableAlias = 'v';
public function get($id)
{
if (empty($id)) {
return ExtenderFacade::execute([static::class, __FUNCTION__], null, func_get_args());
}
$this->select->join('left', '__currencies AS c', 'c.id=v.currency_id');
$variant = parent::get($id);
$variant = $this->resetInfo($variant);
return $variant;
}
public function find(array $filter = [])
{
$this->select->join('left', '__currencies AS c', 'c.id=v.currency_id');
$variants = parent::find($filter);
foreach ($variants as &$variant) {
$variant = $this->resetInfo($variant);
}
return $variants;
}
public function pricesToMainCurrencyByCurrencyId($id)
{
/** @var CurrenciesEntity $currenciesEntity */
$currenciesEntity = $this->entity->get(CurrenciesEntity::class);
$currency = $currenciesEntity->get((int) $id);
$mainCurrency = $currenciesEntity->getMainCurrency();
$mainCurrencyCoef = $this->getMainCurrencyCoef($currency);
$sql = $this->queryFactory->newSqlQuery();
$sql->setStatement("UPDATE ".self::getTable()." SET price=price*{$mainCurrencyCoef}, compare_price=compare_price*{$mainCurrencyCoef}, currency_id=:main_currency_id WHERE currency_id=:currency_id")
->bindValue('currency_id', $id)
->bindValue('main_currency_id', $mainCurrency->id);
$this->db->query($sql);
ExtenderFacade::execute([static::class, __FUNCTION__], null, func_get_args());
}
protected function customOrder($order = null, array $orderFields = [], array $additionalData = [])
{
switch ($order) {
case 'in_stock_first' :
$orderFields = [
'IF(stock=0, 0, 1) DESC',
'position',
'id',
];
break;
}
return ExtenderFacade::execute([static::class, __FUNCTION__], $orderFields, func_get_args());
}
protected function resetInfo($variant)
{
/*Подмена розничной цены на оптовую*/
if($_SESSION['user_id'] && ($user = $this->usersEntity->get(intval($_SESSION['user_id']))) && $user->opt_price){
$variant->price = $variant->opt_price; /*необходимо запихать в условие*/
}
if (empty($variant)) {
return $variant;
}
if (property_exists($variant, 'compare_price') && $variant->compare_price == 0) {
$variant->compare_price = null;
}
if (property_exists($variant, 'stock') && $variant->stock === null) {
$variant->stock = $this->settings->max_order_amount;
}
if (property_exists($variant, 'units') && $variant->units === null) {
$variant->units = $this->settings->units;
}
return $variant;
}
protected function filter__in_stock()
{
$this->select->where('(v.stock > 0 OR v.stock IS NULL)');
}
protected function filter__not_id($id)
{
$this->select->where("id!=:not_id");
$this->select->bindValue('not_id', (int)$id);
}
protected function filter__has_price()
{
$this->select->where("price > 0");
}
private function getMainCurrencyCoef($currency)
{
return $currency->rate_to / $currency->rate_from;
}
}
Добавлено спустя 6 минут 9 секунд:как я понимаю, в этой строчке:
Код: Выделить всё
$user = $this->usersEntity->get(intval($_SESSION['user_id']))
мы присваиваем классу $user результат работы функции класса usersEntity - это так или как то иначе? Может я не все необходимые файлы подключили или еще что-то? Как сделать чтобы $user->opt_price вывел мне значение в файл /Okay/Entities/VariantsEntity.php