Getter not triggered for "AS" field?

22 views
Skip to first unread message

Chad Robinson

unread,
Dec 22, 2015, 2:02:09 PM12/22/15
to Sequelize
Hi folks,

I'm trying to do something like the following in a table definition:

        old_thumbnail: {
            type: DataTypes.STRING(100),
            filters: [],
            get: function() {
                var value = this.getDataValue('old_thumbnail');
                return (value) ? config.assetUrl + value : null;
            }
        },

This works when accessed as-is. The problem is the data model in the API has changed such that the field needs to be output with a new name. I normally do that like this:

    attributes: [..., ['old_thumbnail', 'thumbnail'], ...]

The problem is, when you do this the field getter doesn't "fire" and the raw value is returned instead of the processed one. Short of actually renaming the field in the database, is there a way to get this to work for both use-cases at the same time?

Mick Hansen

unread,
Dec 23, 2015, 5:42:26 AM12/23/15
to Chad Robinson, Sequelize
You can define an attribute with type VIRTUAL. VIRTUALs can be targeted by attribute aliasing and have a custom getter.
With the syntax `new Sequelize.VIRTUAL(Sequelize.STRING, ['old_thumbnail'])` you can also use `attributes: ['thumbnail']` and it will automatically load old_thumbnail as a dependency attribute.
--
Mick Hansen
@mhansendev
mhansen.io

Chad Robinson

unread,
Dec 23, 2015, 12:09:59 PM12/23/15
to Sequelize, task...@gmail.com
Thanks, Mick! That's a really valuable feature. To make this kind of field writable I should just make a setter that .set()'s on the original field?

Mick Hansen

unread,
Dec 24, 2015, 4:53:49 AM12/24/15
to Chad Robinson, Sequelize
Yeah that should work :)
Reply all
Reply to author
Forward
0 new messages