Не корректно работает атрибуты
Не корректно работает атрибуты
Здравствуйте, вообщем наблюдаю такую картинку
Есть у товара атрибуты ( ширина/длина /высота и т.д)
При добавлении уже к созданным атрибутам - дублируются первый атрибут, а последние обрезает по непонятной логике)
Может кто-то стыкался с таким.
В какую сторону смотреть, что может быть.
Есть у товара атрибуты ( ширина/длина /высота и т.д)
При добавлении уже к созданным атрибутам - дублируются первый атрибут, а последние обрезает по непонятной логике)
Может кто-то стыкался с таким.
В какую сторону смотреть, что может быть.
-
- Сообщения: 977
- Зарегистрирован: 2014.08.27, 21:54
Re: Не корректно работает атрибуты
На код смотреть при создании и при обновлении.
Потом смотреть, какие данные пришли при создании, и при добавлении.
Найти разницу.
Потом смотреть, какие данные пришли при создании, и при добавлении.
Найти разницу.
Re: Не корректно работает атрибуты
AtributeContr
ProductController
и модели
atr list model
product model
Код: Выделить всё
public function actionCreate()
{
$model = new AttributeList();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
Код: Выделить всё
public function actionCreate()
{
function deb($v)
{
echo '<pre>';
var_dump($v);
echo '</pre>';
}
$model = new Product();
//default
$model->parent_id = 0;
$model->position = 0;
$model->status = 'active';
$model->bestseller = 'unpopular';
$model->stock = 0;
//dynamic attr
$modelsAttributeLists = [new AttributeList];
$modelsJunction = [new ProductBrandCategory];
if ($model->load(Yii::$app->request->post())) {
//generate translite url
$model->url = Inflector::slug(Inflector::transliterate($model->name), '-', true);
//currency
$model->price_foreign = ArrayHelper::getValue(Yii::$app->request->post(), 'Product.price_foreign');
//dynamic attributes
$modelsAttributeLists = Model::createMultiple(AttributeList::classname());
Model::loadMultiple($modelsAttributeLists, Yii::$app->request->post());
$modelsJunction = Model::createMultiple(ProductBrandCategory::classname());
Model::loadMultiple($modelsJunction, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsAttributeLists) && $valid;
$valid = Model::validateMultiple($modelsJunction) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsAttributeLists as $modelAttributeList) {
$modelAttributeList->product_id = $model->id;
if (!($flag = $modelAttributeList->save(false))) {
$transaction->rollBack();
break;
}
}
foreach ($modelsJunction as $modelJunction) {
$modelJunction->product_id = $model->id;
if (!($flag = $modelJunction->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
$model->save();
} else {
return $this->render('create', [
'model' => $model,
'modelsAttributeLists' => (empty($modelsAttributeLists)) ? [new AttributeList] : $modelsAttributeLists,
'modelsJunction' => (empty($modelsJunction)) ? [new ProductBrandCategory] : $modelsJunction,
]);
}
}
public function actionUpdate($id)
{
function d($v)
{
echo '<pre>';
var_dump($v);
echo '</pre>';
}
$model = $this->findModel($id);
$modelsAttributeLists = $model->attributeLists;
$modelsJunction = $model->junctionTable;
if ($model->load(Yii::$app->request->post())) {
if ($model->url == null) {
//generate translite url
$model->url = Inflector::slug(Inflector::transliterate($model->name), '-', true);
}
//currency
$model->price_foreign = $_POST['Product']['price_foreign'];
//attributeLists
$oldIDs = ArrayHelper::map($modelsAttributeLists, 'id', 'id');
$modelsAttributeLists = Model::createMultiple(AttributeList::classname(), $modelsAttributeLists);
Model::loadMultiple($modelsAttributeLists, Yii::$app->request->post());
$oldBrandIDs = ArrayHelper::map($modelsJunction, 'id', 'id');
$modelsJunction = Model::createMultiple(ProductBrandCategory::classname(), $modelsJunction);
Model::loadMultiple($modelsJunction, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsAttributeLists, 'id', 'id')));
$deletedBrandIDs = array_diff($oldBrandIDs, array_filter(ArrayHelper::map($modelsJunction, 'id', 'id')));
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsAttributeLists) && $valid;
$valid = Model::validateMultiple($modelsJunction) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (!empty($deletedIDs)) {
AttributeList::deleteAll(['id' => $deletedIDs]);
}
foreach ($modelsAttributeLists as $modelAttributeList) {
$modelAttributeList->product_id = $model->id;
if (!($flag = $modelAttributeList->save(false))) {
$transaction->rollBack();
break;
}
}
if (!empty($deletedBrandIDs)) {
ProductBrandCategory::deleteAll(['id' => $deletedBrandIDs]);
}
foreach ($modelsJunction as $modelJunction) {
$modelJunction->product_id = $model->id;
if (!($flag = $modelJunction->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
$model->save();
return $this->render('update', [
'model' => $model,
'modelsAttributeLists' => (empty($modelsAttributeLists)) ? [new AttributeList] : $modelsAttributeLists,
'modelsJunction' => (empty($modelsJunction)) ? [new ProductBrandCategory] : $modelsJunction,
]);
} else {
return $this->render('update', [
'model' => $model,
'modelsAttributeLists' => (empty($modelsAttributeLists)) ? [new AttributeList] : $modelsAttributeLists,
'modelsJunction' => (empty($modelsJunction)) ? [new ProductBrandCategory] : $modelsJunction,
]);
}
}
public function actionDelete($id)
{
$model = $this->findModel($id)->delete();
return $this->redirect(['index']);
}
atr list model
Код: Выделить всё
public function rules()
{
return [
[['product_id'], 'integer'],
[['attr_value', 'attr_id'], 'safe'],
[['attr_value'], 'string', 'max' => 255],
[['product_id'], 'exist', 'skipOnError' => true, 'targetClass' => Product::className(), 'targetAttribute' => ['product_id' => 'id']],
[['attr_id'], 'exist', 'skipOnError' => true, 'targetClass' => AttributeName::className(), 'targetAttribute' => ['attr_id' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'attr_id' => 'Название атрибута',
'attr_value' => 'Значение атрибута',
'product_id' => 'Продукт',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getProduct()
{
return $this->hasOne(Product::className(), ['id' => 'product_id']);
}
public function getAttr()
{
return $this->hasOne(AttributeName::className(), ['id' => 'attr_id']);
}
product model
Код: Выделить всё
public function getAttributeLists()
{
return $this->hasMany(AttributeList::className(), ['product_id' => 'id']);
}
public function getJunctionTable()
{
return $this->hasMany(ProductBrandCategory::className(), ['product_id' => 'id']);
}
Последний раз редактировалось dps_guest 2019.04.10, 18:17, всего редактировалось 1 раз.
-
- Сообщения: 977
- Зарегистрирован: 2014.08.27, 21:54
Re: Не корректно работает атрибуты
Вы можете это прочитать?
Используйте тег code.
Используйте тег code.
Re: Не корректно работает атрибуты
"Порядок для дураков, гении господствуют над хаосом" (с). Немножко оффтопа, но если честно читать действительно невозможно.
И тут скорее нужен код моделей, а не контроллеров
И тут скорее нужен код моделей, а не контроллеров
Re: Не корректно работает атрибуты
бро юзай [/code]
Код: Выделить всё
[code]
Re: Не корректно работает атрибуты
обновил выше
Последний раз редактировалось dps_guest 2019.04.10, 18:17, всего редактировалось 1 раз.
Re: Не корректно работает атрибуты
будут у кого-то идеи в чем трабл может быть?(
Re: Не корректно работает атрибуты
Может у кого-то появилась идея? )
Тема поднималась пользователем dps_guest 2019.05.06, 11:34.