sanevys sanevys - 4 years ago 215
Android Question

GreenDao query with LIKE clause in related object

How to use green dao query to query objects, that has LIKE sting in related object?

QueryBuilder qb = mainDao.queryBuilder();
qb.where(
mainDao.Properties.Date.between(filter.getFrom().getTime(), filter.getTo().getTime()),
qb.or(mainDao.Properties.Details.like("%"+ string + "%"),
infoDao.Properties.Display_name.like("%" + string + "%"),
infoDao.Properties.Email.like("%" + string + "%"),
infoDao.Properties.Phone.like("%" + string + "%"),
infoDao.Properties.Code.like("%" + string + "%")));


This kind of query constructed by me will not work? Any suggestions how I could managed a query that checks related field properties for occurrences?

MainDao has foregin key of InfoDao

I think I want to do something like this:

SELECT *
FROM Main
INNER JOIN Info
ON Main.InfoID=Info.InfoID;
WHERE Info.SomeField LIKE "%string%"

Answer Source

I don't know if it's the best solution but, since greendao doesn't support JOIN, it could do the trick. Also, you could simply use a SQLite query for this particular case.

Here I'm assuming that you have a relation between Main and Info. If you don't, you could do it with a few more steps.

List<Info> infoArray = infoDao.queyBuilder()
    .whereOr(infoDao.Properties.Display_name.like("%" + string + "%"),
        infoDao.Properties.Email.like("%" + string + "%"),
        infoDao.Properties.Phone.like("%" + string + "%"),
        infoDao.Properties.Code.like("%" + string + "%"))
    .list();

List<Main> mainArray = Collections.emptyList();
for (Info info : infoArray) {
    if(!mainArray.contains(info.getMain()) {
        mainArray.add(info.getMain());
    }
}

[UPDATED]

If you don't have a relation from Info to Main, there's another version:

List<Info> infoArray = infoDao.queryBuilder()
    .whereOr(infoDao.Properties.Display_name.like("%" + string + "%"),
        infoDao.Properties.Email.like("%" + string + "%"),
        infoDao.Properties.Phone.like("%" + string + "%"),
        infoDao.Properties.Code.like("%" + string + "%"))
    .list();

List<Long> infoIds= Collections.emptyList();
for (Info info : infoArray) {
    infoIds.add(info.getId());
}

List<Main> mainArray = mainDao.queryBuilder()
    .whereOr(mainDao.Properties.id.in(infoIds),
        mainDao.Properties.Details.like("%"+ string + "%"))
    .list();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download