In my app the relationship is designed like this: and I want to select at least one user as a friend for all chats.
Basically, I want to execute the following query:\
SELECT c.* FROM CHAT c, USER u, UserChats uc WHERE c.type = myType AND u.isFriend = 1 AND c.id = uc.chatId AND u.id = uc.userId
I haven't managed to find a way to do this in the GreenDao library, hopefully someone can help me with this.
EDIT:
This is what I have so far:
List<UsersChats> list = usersChatsDao.queryDeep( "WHERE T0." + UserDao.Properties.isFriend.collumnName + " = ? "+ "AND T1." + ChatDao.Properties.type.collumName + " = ?", new String[] {"1", myType}); if(list != null && list.isEmpty() == false) { List<Chat> chats = new ArrayList<Chat>(); for(UsersChats link : list) { chats.add(link.getChat()); } }
Solution 1:
Since grrendao doesn't do the QueryBuilder.join()
current method, I think your solution is the best one you can find right now, it uses joins internally.
There are only minor drawbacks to it:
- You may query more tables than you actually need
- You're iterating over a potentially huge list
- you cannot use
listLazy()
Another way is to use some query like this (assume IsFriend
yes int-column
and myType
fit to ChatDao.Properties.type
:
Query<Chat> qc = chatDao.queryRawCreate( " LEFT JOIN "+UserChatsDao.TABLENAME+" UC"+ " ON T."+ChatDao.Properties.id.columnName+"=UC."+UserChats.Properties.chatId.columnName+ " LEFT JOIN "+UserDao.TABLENAME+" U"+ " ON UC."+UserChats.Properties.userId.columnName+"=U."UserDao.Properties.id.columnName+ " WHERE U."UserDao.Properties.isFriend.columnName+"=?"+ " AND T."+ChatDao.Properties.type.columnName+"=?", 1, myType);
Or (presumably less performance, etc.):
Query<Chat> qc = chatDao.queryRawCreate( " , "+UserChatsDao.TABLENAME+" UC"+ " , "+UserDao.TABLENAME+" U"+ " WHERE T."+ChatDao.Properties.type.columnName+"=?"+ " AND U."+UserDao.Properties.isFriend.columnName+"=?"+ " AND T."+ChatDao.Properties.id.columnName+"=UC."+UserChats.Properties.chatId.columnName+ " AND U."UserDao.Properties.id.columnName+"=UC."+UserChats.Properties.userId.columnName, myType, 1);
Then you can use the desired list()
-method:
qc.list();
qc.listLazy ();
...