G
G
Georgy Baruchyan2019-11-16 13:03:20
1C-Bitrix
Georgy Baruchyan, 2019-11-16 13:03:20

How to avoid incorrect data typing when working with ORM?

Hello.
When working with ORM and the query object, there is a small (more precisely, a very big) nuisance: all fields become of type string, although in essence they are described with the correct data. Example:

$select = [
            '*',
            'IMG_' => 'IMG',
            'SECTION.ID', 
        ];

        $query = Sale\Internals\BasketTable::query()
            
            ->registerRuntimeField('SECTION', array(
                'data_type' => \Bitrix\Iblock\SectionTable::class,
                'reference' => [
                    '=this.PRODUCT.IBLOCK_SECTION_ID' => 'ref.ID'
                ]
            ))
            ->registerRuntimeField('IMG', [
                'data_type' => \Bitrix\Main\FileTable::class,
                'reference' => [
                    '=this.PRODUCT.PREVIEW_PICTURE' => 'ref.ID',
                ]
            ])
            ->setSelect($select)
            ->where('FUSER_ID', $this->fuser)
            ->where('ORDER_ID', null)

        ;

        $rsBasketItems = $query->exec();

        while($basketItem = $rsBasketItems->fetch()){
        }

If you dump basketItem, then all fields will be of type string.
If you use fetchObject, then inside the data is correctly typed, but I don’t like working with them, because resulting in very heavy objects. Well, it's very inconvenient to access each field like $basketItem->get('field') . + z I use my own models, in which I make all the transformations, and display them in the template.
Alternatively, you can still use addFetchDataModifier and convert the necessary fields there, but this is also not very convenient.
Who faced, how did you solve?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Nikolaev, 2019-11-16
@gromdron

If you dump basketItem, then all fields will be of type string

Correctly. This limitation is not caused by the bitrix framework, but by the driver for working with the DBMS. The database stores real values, but mysqli returns string results.
Those. they already come to Bitrix from the DBMS.
Objects solve this problem by casting results to the required types, while raw values ​​remain strings.
If you want, you can pass the \Bitrix\Main\Text\Converter descendant class to $rsBasketItems->fetch() and encode it can be applied to each value and you will immediately get the fields you need, but if you need to do it in one place , then it will be easier, of course, to run through the cycle and bring it on your own.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question