| 111 | }; |
| 112 | |
| 113 | function extendInstance(Model, Instance, Driver, association, opts) { |
| 114 | var promiseFunctionPostfix = Model.settings.get('promiseFunctionPostfix'); |
| 115 | |
| 116 | Object.defineProperty(Instance, association.hasAccessor, { |
| 117 | value : function (cb) { |
| 118 | if (!Instance[Model.id]) { |
| 119 | cb(new ORMError("Instance not saved, cannot get extension", 'NOT_DEFINED', { model: Model.table })); |
| 120 | } else { |
| 121 | association.model.get(util.values(Instance, Model.id), function (err, extension) { |
| 122 | return cb(err, !err && extension ? true : false); |
| 123 | }); |
| 124 | } |
| 125 | return this; |
| 126 | }, |
| 127 | enumerable : false |
| 128 | }); |
| 129 | Object.defineProperty(Instance, association.getAccessor, { |
| 130 | value: function (opts, cb) { |
| 131 | if (typeof opts == "function") { |
| 132 | cb = opts; |
| 133 | opts = {}; |
| 134 | } |
| 135 | |
| 136 | if (!Instance[Model.id]) { |
| 137 | cb(new ORMError("Instance not saved, cannot get extension", 'NOT_DEFINED', { model: Model.table })); |
| 138 | } else { |
| 139 | association.model.get(util.values(Instance, Model.id), opts, cb); |
| 140 | } |
| 141 | return this; |
| 142 | }, |
| 143 | enumerable : false |
| 144 | }); |
| 145 | Object.defineProperty(Instance, association.setAccessor, { |
| 146 | value : function (Extension, cb) { |
| 147 | Instance.save(function (err) { |
| 148 | if (err) { |
| 149 | return cb(err); |
| 150 | } |
| 151 | |
| 152 | Instance[association.delAccessor](function (err) { |
| 153 | if (err) { |
| 154 | return cb(err); |
| 155 | } |
| 156 | |
| 157 | var fields = Object.keys(association.field); |
| 158 | |
| 159 | if (!Extension.isInstance) { |
| 160 | Extension = new association.model(Extension); |
| 161 | } |
| 162 | |
| 163 | for (var i = 0; i < Model.id.length; i++) { |
| 164 | Extension[fields[i]] = Instance[Model.id[i]]; |
| 165 | } |
| 166 | |
| 167 | Extension.save(cb); |
| 168 | }); |
| 169 | }); |
| 170 | return this; |