Data pre-manipulation when getting from database
- uestla
- Backer | 799
Hi.
I have some serialized data in a certain column in the database table, so what I'm trying to do is unserialize this data even before they're returned by the Nette\Database layer.
The main idea was just to inherit the Selection
class and
overwrite the fetch()
method, but it seems not to be working when
accessing the data in a foreach
loop.
Here's my code:
use Nette\Database\Table\Selection;
class StuffSelection extends Selection
{
/**
* @return Nette\Database\Table\ActiveRow|FALSE
*/
function fetch()
{
$rec = parent::fetch();
if (!$rec) return FALSE;
$rec->variants = unserialize($rec->variants); // the serialized column
}
}
But when I looked then in the API documentation, the fetch()
method isn't called within the foreach
loop, am I right?
Is there any working way how to do it (and pls – Doctrine or M:N data storing is not the answer here…)?
Thanks.
- uestla
- Backer | 799
Well, the solution's been found quite quickly :-)
Hope it helps somebody else as well… So the key method wasn't
fetch()
, but createRow()
, which is called within the
execute()
method.
Here's the update:
use Nette\Database\Table;
class StuffSelection extends Table\Selection
{
/**
* @param array
* @return Table\ActiveRow
*/
protected function createRow(array $row)
{
if (isset($row['variants']))
$row['variants'] = unserialize($row['variants']);
return parent::createRow($row);
}
}
Last edited by uestla (2012-04-17 13:19)
- hrach
- Member | 1838
Well, it would work correctly only in the primary selection instance.
I have solution for your problem. It's called Ndab and it's orm based on Nette\Database (currently on my feature branch, I hope David will merge it).
class YourEntity extends Ndab\Entity
{
public function getVariants()
{
return unserialize($this->variants);
}
}