M
M
Mark2018-07-18 03:59:19
Yii
Mark, 2018-07-18 03:59:19

How to competently implement the functionality of individual prices in Yii2?

Task: to implement individual prices for services for some users. Not every service can have its own individual price (that is, if there is no individual price, display the standard one).
Simplified table schema:
e7OwvKu.png

text

Таблица: user
Поля: id(type: integer, lenght: 11, AutoIncrement)
Таблица: service
Поля: id(integer, 11, AI), price(float)
Таблица: individual_price
Поля: id(integer, 11, AI), service(integer, 11, relation service.id), user(integer, 11, relation user.id), price(float)
Ideas/approaches I've been thinking about:
1. Using the AttributeBehaivo r behavior along with the "afterFind" event. The problem is that this behavior handles each individual database record individually, and when getting individual prices, the corresponding number of requests is generated. Read more here .
2. Organize a separate method where the result of the price request will be placed, get individual prices by user ID and change the price of services in a cycle, eventually returning an object with changed prices. There are a number of disadvantages, ranging from the fact that you have to make methods for many variations, problems with joinWith, and also unsafe.
UPD 10/07/18: The question is relevant. Updated and better structured.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Kim, 2018-07-18
@kimono

SELECT `services`.*, `prices`.`amount` FROM `services`
LEFT JOIN `prices` ON `prices`.`service_id` = `services`.`id` AND `prices`.`user_id` = 100

Services::find()->select(['services.*', 'prices.amount'])->leftJoin('prices', ['AND',
  'services.id = prices.amount',
  ['prices.user_id' => Yii::$app->user->id],
])->asArray()->all();

M
Maxim Timofeev, 2018-10-07
@webinar

The actual price must be a method in the services. And in this method already implement all the magic. I think this will be a connection with individual_price, checking if there is one and if not setting the base one.
Further on afterFind: what prevents using mass saving through for example:
https://www.yiiframework.com/doc/api/2.0/yii-db-ac...
and I don’t quite understand why and how you added AttributeBehavior here by sampling from the database, everything was correctly suggested by Dmitry Kim

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question