I need to recognize, on saving a record, if a similar record has been created less than 15 minutes ago. If it has, I don’t need to save the new record, I need instead to load the similar record.
Use Case: A price is calculated (and some price records are inserted) upon the saving of a PriceRequest. A PriceRequest is valid for 15 minutes, subsequent requests should not be saved: the action of saving a new analog request will load the previous still valid request.
I have a working solution for this problem, but it is in the Controller (alas, in multiple controllers…):
//in controller
$request = PriceRequest::model()->findByAttributes(
[...]
,
'created > DATE_SUB(NOW(), INTERVAL 15 MINUTE)'
);
if (is_null($request))
{
$request = new PriceRequest();
[...]
$request->save();
}
I want to move this logic to the model’s beforeSave, if possible.
Is it possible?
I can do
//in the model
protected function beforeSave()
{
[...]
//look for similar request made in the last 15 minutes.
$previous = self::model()->findByAttributes(array(
[...]
), 'created > DATE_SUB(NOW(), INTERVAL 15 MINUTE)'
);
if (!is_null($request))
{
$this = $previous;
return false;
}
[...]
return true;
}
but obviously the $this = $previous does not work…
Can anyone help me?