Extended logic for tables with two relations to the same database. Make use of alias inside the queries

This commit is contained in:
Eike Bartels 2018-02-26 14:55:42 +01:00
parent 23f776c2f9
commit 3c8e368188
3 changed files with 13 additions and 8 deletions

View file

@ -229,19 +229,20 @@ class PostgresOrmGenerator extends GeneratorForAnnotation<ORM> {
buf.write(ctx.prefix + "$name");
});
int relationCounter = 0;
// Add all relationship fields...
for (var name in ctx.relationships.keys) {
// Should only run when a JOIN is performed, i.e. singular
var relationship = ctx.populateRelationship(name);
if (relationship.isSingular) {
var modelTypeContext = await relationship.modelTypeContext;
modelTypeContext.fields.forEach((f) {
if (i++ > 0) buf.write(', ');
var name = modelTypeContext.resolveFieldName(f.name);
buf.write('${relationship.foreignTable}.$name');
buf.write('rel$relationCounter.$name');
});
}
relationCounter++;
}
return buf.toString();
@ -265,17 +266,16 @@ class PostgresOrmGenerator extends GeneratorForAnnotation<ORM> {
var relationsIfThen = ifThen(prefix.equals(literal(null)));
int relationCounter = 0;
// Apply relationships
ctx.relationships.forEach((name, r) {
var relationship = ctx.populateRelationship(name);
if (relationship.isSingular) {
String b = ' LEFT OUTER JOIN ${relationship.foreignTable} ON ${ctx
.tableName}.${relationship.localKey} = ${relationship
.foreignTable}.${relationship.foreignKey}';
String b = ' LEFT OUTER JOIN ${relationship.foreignTable} AS rel$relationCounter ON ${ctx
.tableName}.${relationship.localKey} = rel$relationCounter.${relationship.foreignKey}';
relationsIfThen.addStatement(buf.invoke('write', [literal(b)]));
}
relationCounter++;
// A join-based solution won't work for hasMany and co.
/*else {
String b = ' LEFT OUTER JOIN ${relationship.foreignTable} ON ${ctx

View file

@ -12,6 +12,7 @@ import 'common.dart';
main() {
PostgreSQLConnection connection;
Author rowling;
Author jameson;
Book deathlyHallows;
setUp(() async {
@ -19,10 +20,11 @@ main() {
// Insert an author
rowling = await AuthorQuery.insert(connection, name: 'J.K. Rowling');
jameson = await AuthorQuery.insert(connection, name: 'J.K. Jameson');
// And a book
deathlyHallows = await BookQuery.insert(connection,
authorId: int.parse(rowling.id), name: 'Deathly Hallows');
authorId: int.parse(rowling.id), name: 'Deathly Hallows', partnerAuthorId: int.parse(jameson.id));
});
tearDown(() => connection.close());

View file

@ -12,6 +12,9 @@ class _Book extends Model {
@belongsTo
Author author;
@BelongsTo(localKey: "partner_author_id")
Author partnerAuthor;
int authorId;
String name;
}