N
N
Nikita Roschenko2017-03-21 14:39:45
MySQL
Nikita Roschenko, 2017-03-21 14:39:45

How to organize dynamic product parameters in yii2 using ActiveRecord?

Good day, there are 2 tables product (id, name, type, create_at, etc...) and product_params (id, product_id, name, value).
The bottom line is that the product table stores general information about products, and the product_params table stores specific parameters depending on the product type. I would like to organize work with product_params as an ActiveRecord object and not as an array of these objects.
That is, something like this:

$productParams = ProductParams::findOne(['product_id' => 1]);
$productParams->weight = 10;
$productParams->color = 'blue';
$productParams->size = 200;
$productParams->save();

And when saving, the following records were obtained in the product_params table :
id | product_id       | name   | value 
1  | 1                | weight | 10
2  | 1                | color  | blue
3  | 1                | size   | 200

I understand that this is contrary to the ActiveRecord ideology, but perhaps there are already some solutions for this type of task (Google did not help, unfortunately, although it may not have been Googled in the same way)?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2017-03-21
@webinar

If I understand you correctly, it looks like this:

public function getProductParams(){
// тут связь has many
}

public function getParam($name=color){
return $this->getProductParams()->andWhere(['name'=>$name])->one();
//или сразу value а не объект
// return $this->getProductParams()->andWhere(['name'=>$name])->one()->value;
}

as an option, you can already split the array of objects from getProductParams() in the php model and write it to a public variable using afterFind, for example

M
Maxim Fedorov, 2017-03-21
@qonand

The main question is why? why do you want to do that? what will it give you?
If it's just something - then you're on your way to creating shitty code. If, for example, you need to edit these parameters, then it is better to use a dynamic model for these purposes .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question