| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509 |
2
2
46
44
44
44
2
1
2
2
1
1
19
4
15
15
15
15
1
14
14
7
14
14
14
14
1
2
8
3
15
15
3
3
3
3
1
1
1
1
1
1
1
2
2
2
2
8
8
8
8
8
8
8
8
8
8
8
8
12
12
14
12
12
15
12
12
2
14
12
15
12
6
10
4
6
4
2
2
14
1
1
1
31
5
26
26
26
26
2
26
26
1
25
25
3
22
22
22
1
6
12
3
26
25
3
3
1
1
1
1
1
1
1
6
6
6
5
6
2
3
3
2
3
3
3
3
1
2
2
3
1
1
12
12
12
12
12
12
12
12
4
4
4
12
10
10
7
10
10
4
4
4
4
4
6
6
1
5
5
5
5
5
5
12
5
5
5
1
5
5
5
5
2
2
3
5
5
| /**
* 高级模型
* @return {[type]} [description]
*/
module.exports = Model(function(){
'use strict';
return {
/**
* 关联定义
* 数据格式:
* 'Profile': {
type: 1, //类型
model: 'Profile', //对应的模型名
name: 'Profile', //获取数据后,追加到原有数据里的key
key: 'id',
fKey: 'user_id', //关联的key
field: 'id,name',
where: 'name=xx',
order: '',
limit: ''
* }
* @type {Object}
*/
relation: {},
/**
* 本次使用的关联名称,默认是全部使用
* @type {Boolean}
*/
_relationName: true,
/**
* 设置本次使用的relation
* @param {[type]} name [description]
*/
setRelation: function(name, value){
if (isObject(name) || !isEmpty(value)) {
var obj = isObject(name) ? name : getObject(name, value);
extend(this.relation, obj);
return this;
}
if (isString(name)) {
name = name.split(',');
}
this._relationName = name || {};
return this;
},
/**
* find后置操作
* @param {[type]} data [description]
* @return {[type]} [description]
*/
_afterFind: function(data, options){
return this.getRelation(data, options);
},
/**
* select后置操作
* @param {[type]} data [description]
* @return {[type]} [description]
*/
_afterSelect: function(data, options){
return this.getRelation(data, options);
},
/**
* 获取关联的数据
* @param {[type]} data [description]
* @param Boolean isDataList 是否是数据列表
* @return {[type]}
*/
getRelation: function(data, options){
if (isEmpty(data) || isEmpty(this.relation) || isEmpty(this._relationName)) {
return data;
}
var self = this;
options = options || {};
var promises = Object.keys(this.relation).map(function(key){
//如果不在开启的relation内,则直接返回
if (self._relationName !== true && self._relationName.indexOf(key) === -1) {
return;
}
var item = self.relation[key];
if (!isObject(item)) {
item = {type: item};
}
var model = D(item.model || key);
model.cache(options.cache).where(item.where).field(item.field).order(item.order).limit(item.limit);
var opts = extend({
name: key,
model: model,
type: 1,
key: self.getPk(),
fKey: self.name.toLowerCase() + '_id'
}, item);
switch(item.type){
case 2:
return self._getBelongsToRelation(data, opts, options);
case 3:
return self._getHasManyRelation(data, opts, options);
case 4:
return self._getManyToManyRelation(data, opts, options);
default:
return self._getHasOneRelation(data, opts, options);
}
});
return Promise.all(promises).then(function(){
return data;
});
},
/**
* 一对一
* @param {[type]} data [description]
* @param {[type]} value [description]
* @param {[type]} mapOptions [description]
* @return {[type]} [description]
*/
_getHasOneRelation: function(data, mapOpts/*, options*/){
var self = this;
var where = self.parseRelationWhere(data, mapOpts);
// if (where === false) {
// return {};
// }
return mapOpts.model.where(where).select().then(function(mapData){
return self.parseRelationData(data, mapData, mapOpts);
});
},
/**
* 一对一,属于
* @param {[type]} data [description]
* @param {[type]} mapOpts [description]
* @param {[type]} options [description]
* @return {[type]} [description]
*/
_getBelongsToRelation: function(data, mapOpts/*, options*/){
var self = this;
return mapOpts.model.getTableFields().then(function(){
mapOpts.key = mapOpts.model.getModelName().toLowerCase() + '_id';
mapOpts.fKey = mapOpts.model.getPk();
var where = self.parseRelationWhere(data, mapOpts);
// if (where === false) {
// return {};
// }
return mapOpts.model.where(where).select().then(function(mapData){
return self.parseRelationData(data, mapData, mapOpts);
})
})
},
/**
* 一对多
* @param {[type]} data [description]
* @param {[type]} value [description]
* @param {[type]} mapOptions [description]
* @return {[type]} [description]
*/
_getHasManyRelation: function(data, mapOpts/*, options*/){
var self = this;
var where = self.parseRelationWhere(data, mapOpts);
// if (where === false) {
// return [];
// }
return mapOpts.model.where(where).select().then(function(mapData){
return self.parseRelationData(data, mapData, mapOpts, true);
});
},
/**
* 多对多
* @param {[type]} data [description]
* @param {[type]} value [description]
* @param {[type]} mapOptions [description]
* @param {[type]} parsedOptions [description]
* @return {[type]} [description]
*/
_getManyToManyRelation: function(data, mapOpts, options){
var self = this;
return mapOpts.model.getTableFields().then(function(){
var where = self.parseRelationWhere(data, mapOpts);
// if (where === false) {
// return [];
// }
//关联的实体表和关系表联合查询
var sql = 'SELECT %s, a.%s FROM %s as a, %s as b %s AND a.%s=b.%s %s';
//获取要查询的字段
var field = self.db.parseField(mapOpts.field).split(',').map(function(item){
return 'b.' + item;
}).join(',');
var queryData = [
field,
mapOpts.fKey,
mapOpts.rTable || self.getRelationTableName(mapOpts.model),
mapOpts.model.getTableName(),
self.db.parseWhere(where),
mapOpts.rfKey || (mapOpts.model.getModelName().toLowerCase() + '_id'),
mapOpts.model.getPk(),
mapOpts.where ? (' AND ' + self.db.parseWhere(mapOpts.where).trim().slice(6)) : ''
];
sql = self.parseSql(sql, queryData);
return self.db.select(sql, options.cache).then(function(mapData){
return self.parseRelationData(data, mapData, mapOpts, true);
});
});
},
/**
* 多对多关系下,获取对应的关联表
* @return {[type]} [description]
*/
getRelationTableName: function(model){
var table = [
this.tablePrefix,
this.tableName || this.name,
'_',
model.getModelName()
].join('');
return table.toLowerCase();
},
/**
* 多堆垛关系下,回去对应关联表的模型
* @param {[type]} model [description]
* @return {[type]} [description]
*/
getRelationModel: function(model){
var name = ucfirst(this.tableName || this.name) + ucfirst(model.getModelName());
return D(name);
},
/**
* 解析relation的where条件
* @param {[type]} data [description]
* @param {[type]} mapKey [description]
* @param {[type]} mapfKey [description]
* @return {[type]} [description]
*/
parseRelationWhere: function(data, mapOpts){
if (isArray(data)) {
var keys = {};
data.forEach(function(item){
keys[item[mapOpts.key]] = 1;
})
var value = Object.keys(keys);
// if (value.length === 0) {
// return false;
// }
return getObject(mapOpts.fKey, ['IN', value]);
}
return getObject(mapOpts.fKey, data[mapOpts.key]);
},
/**
* 解析查询后的数据
* @param {[type]} data [description]
* @param {[type]} mapData [description]
* @param {[type]} mapName [description]
* @param {[type]} mapKey [description]
* @param {[type]} mapfKey [description]
* @param {Boolean} isArrMap [description]
* @return {[type]} [description]
*/
parseRelationData: function(data, mapData, mapOpts, isArrMap){
if (isArray(data)) {
//提前初始化,防止mapData为空导致data里的数据没有初始化的情况
data.forEach(function(item, i){
data[i][mapOpts.name] = isArrMap ? [] : {};
});
mapData.forEach(function(mapItem){
data.forEach(function(item, i){
if (mapItem[mapOpts.fKey] !== item[mapOpts.key]) {
return;
}
if (isArrMap) {
data[i][mapOpts.name].push(mapItem);
}else{
data[i][mapOpts.name] = mapItem;
}
});
});
}else{
data[mapOpts.name] = isArrMap ? mapData : (mapData[0] || {});
}
return data;
},
/**
* 添加后置操作
* @param {[type]} data [description]
* @param {[type]} parsedOptions [description]
* @return {[type]} [description]
*/
_afterAdd: function(data, parsedOptions){
return this.postRelation('ADD', data, parsedOptions);
},
/**
* 删除后置操作
* @param {[type]} data [description]
* @param {[type]} parsedOptions [description]
* @return {[type]} [description]
*/
_afterDelete: function(data, parsedOptions){
return this.postRelation('DELETE', data, parsedOptions);
},
/**
* 更新后置操作
* @param {[type]} data [description]
* @param {[type]} parsedOptions [description]
* @return {[type]} [description]
*/
_afterUpdate: function(data, parsedOptions){
return this.postRelation('UPDATE', data, parsedOptions);
},
/**
* 提交类关联操作
* @param {[type]} postType [description]
* @param {[type]} data [description]
* @param {[type]} parsedOptions [description]
* @return {[type]} [description]
*/
postRelation: function(postType, data/*, parsedOptions*/){
if (isEmpty(data) || isEmpty(this.relation) || isEmpty(this._relationName)) {
return data;
}
var self = this;
var promises = Object.keys(this.relation).map(function(key){
var item = self.relation[key];
if (!isObject(item)) {
item = {type: item};
}
var opts = extend({
type: 1,
postType: postType,
name: key,
key: self.getPk(),
fKey: self.name.toLowerCase() + '_id'
}, item);
//如果没有开启对应的relation,则直接返回
if (self._relationName !== true && self._relationName.indexOf(opts.name) === -1) {
return;
}
var mapData = data[opts.name];
//如果没有对应的数据,则直接返回
if (isEmpty(mapData) && postType !== 'DELETE' || isEmpty(data[opts.key])) {
return;
}
opts.data = mapData;
opts.model = D(item.model || key).where(item.where);
switch(item.type){
case 2:
return self._postBelongsToRelation(data, opts);
case 3:
return self._postHasManyRelation(data, opts);
case 4:
return self._postManyToManyRelation(data, opts);
default:
return self._postHasOneRelation(data, opts);
}
});
return Promise.all(promises).then(function(){
return data;
});
},
/**
* 一对一提交
* @param {[type]} data [description]
* @param {[type]} value [description]
* @param {[type]} mapOptions [description]
* @param {[type]} parsedOptions [description]
* @return {[type]} [description]
*/
_postHasOneRelation: function(data, mapOpts){
var where;
switch(mapOpts.postType){
case 'ADD':
mapOpts.data[mapOpts.fKey] = data[mapOpts.key];
return mapOpts.model.add(mapOpts.data);
case 'DELETE':
where = getObject(mapOpts.fKey, data[mapOpts.key]);
return mapOpts.model.where(where).delete();
case 'UPDATE':
where = getObject(mapOpts.fKey, data[mapOpts.key]);
return mapOpts.model.where(where).update(mapOpts.data);
}
},
/**
* 一对一属于
* @param {[type]} data [description]
* @return {[type]} [description]
*/
_postBelongsToRelation: function(data){
return data;
},
/**
* 一对多提交
* @param {[type]} data [description]
* @param {[type]} value [description]
* @param {[type]} mapOptions [description]
* @param {[type]} parsedOptions [description]
* @return {[type]} [description]
*/
_postHasManyRelation: function(data, mapOpts){
var mapData = mapOpts.data;
var model = mapOpts.model;
if (!isArray(mapData)) {
mapData = [mapData];
}
switch(mapOpts.postType){
case 'ADD':
mapData = mapData.map(function(item){
item[mapOpts.fKey] = data[mapOpts.key];
return item;
});
return model.addAll(mapData);
case 'UPDATE':
return model.getTableFields().then(function(){
var pk = model.getPk();
var promises = mapData.map(function(item){
if (item[pk]) {
return model.update(item);
}else{
item[mapOpts.fKey] = data[mapOpts.key];
//添加不成功则自动忽略,不报错
return model.add(item).catch(function(){});
}
});
return Promise.all(promises);
});
case 'DELETE':
var where = getObject(mapOpts.fKey, data[mapOpts.key]);
return model.where(where).delete();
}
},
/**
* 多对多提交
* @param Object data [description]
* @param object value [description]
* @param {[type]} mapOptions [description]
* @param {[type]} parsedOptions [description]
* @return {[type]} [description]
*/
_postManyToManyRelation: function(data, mapOpts){
var self = this;
var model = mapOpts.model;
var promise = model.getTableFields();
var rfKey = mapOpts.rfKey || (model.getModelName().toLowerCase() + '_id');
var type = mapOpts.postType;
var mapData = mapOpts.data;
var relationModel = self.getRelationModel(model);
if (type === 'DELETE' || type === 'UPDATE') {
promise = promise.then(function(){
var where = getObject(mapOpts.fKey, data[mapOpts.key]);
return relationModel.where(where).delete();
});
}
if (type === 'ADD' || type === 'UPDATE') {
promise = promise.then(function(){
if (!isArray(mapData)) {
mapData = isString(mapData) ? mapData.split(',') : [mapData];
}
var firstItem = mapData[0];
//关系数据
if (isNumberString(firstItem) || (isObject(firstItem) && (rfKey in firstItem))) {
//生成要更新的数据
var postData = mapData.map(function(item){
var key = [mapOpts.fKey, rfKey];
var val = [data[mapOpts.key], item[rfKey] || item];
return getObject(key, val);
});
return relationModel.addAll(postData);
}else{ //实体数据
var unqiueField = model.getUniqueField();
if (!unqiueField) {
return getPromise(new Error('table `' + model.getTableName() + '` has no unqiue field'), true);
}
return self._getRalationAddIds(mapData, model, unqiueField).then(function(ids){
var postData = ids.map(function(id){
var key = [mapOpts.fKey, rfKey];
var val = [data[mapOpts.key], id];
return getObject(key, val);
});
return relationModel.addAll(postData);
});
}
});
}
return promise;
},
/**
* 插入数据,并获取插入的id集合
* @param {[type]} dataList [description]
* @param {[type]} model [description]
* @param {[type]} unqiueField [description]
* @return {[type]} [description]
*/
_getRalationAddIds: function(dataList, model, unqiueField){
var ids = [];
var promises = dataList.map(function(item){
if (!isObject(item)) {
item = getObject(unqiueField, item);
}
var value = item[unqiueField];
var where = getObject(unqiueField, value);
return model.where(where).field(model.getPk()).find().then(function(data){
if (isEmpty(data)) {
return model.add(item).then(function(insertId){
ids.push(insertId);
});
}else{
ids.push(data[model.getPk()]);
}
});
});
return Promise.all(promises).then(function(){
return ids;
});
}
};
}); |