MrFisherman
MrFisherman

Reputation: 738

Get field from table by giving field from another table (Room Library)

I am learning how to use Room in Android. I have two tables: KeyWordsTable (id, keyword) and CategoriesTable (id, imagePath). I want to do something like this: user give a keyword -> checking which category it belongs to -> get imagePath from CategoriesTable.

I have @Dao interface and i did something like

@Query("SElECT image_path AS imagePath FROM CategoriesTable JOIN KeywordsTable ON idKeyWords = idCategories WHERE category_name = :categoryName LIMIT 1")

CategoriesTable findImagePathByKeyWordName(String categoryName);

Is it correct solution? Will I get imagePath by giving a keyword?

Thank you in advice :)

CategoriesTable.class

@Entity
public class CategoriesTable {
@NonNull
@PrimaryKey(autoGenerate = true)
private int idCategories;

@ColumnInfo(name = "category_name")
private String categoryName;

@ColumnInfo(name = "image_path")
private String imagePath;
//getters and setters

KeywordsTable.class

@Entity
public class KeywordsTable {
@PrimaryKey(autoGenerate = true)
private int idKeyWords;

@ColumnInfo(name = "keywords_name")
private String keywordsName;
//getters and setters

Upvotes: 0

Views: 1343

Answers (1)

mrJoe
mrJoe

Reputation: 500

First, you must provide foreign key on the many side of the relation. Moreover, you should set name of each table in their @Entity annotation.

KeywordsTable.java

@Entity(tableName = "keywords",
        foreignKeys = @ForeignKey(entity = CategoriesTable.class,
                                  parentColumns = "idCategories",
                                  childColumns = "categoryId",
                                  onDelete = CASCADE))
public class KeywordsTable {
    @PrimaryKey(autoGenerate = true)
    private int idKeyWords;

    @ColumnInfo(name = "keywords_name")
    private String keywordsName;

    private int categoryId;

    //getters and setters
}

CategoriesTable.java

@Entity(tableName = "categories")
public class CategoriesTable {
    @PrimaryKey(autoGenerate = true)
    private int idCategories;

    @ColumnInfo(name = "category_name")
    private String categoryName;

    @ColumnInfo(name = "image_path")
    private String imagePath;
    //getters and setters
}

Method in dao interface should look like this:

@Query("SELECT image_path FROM categories INNER JOIN keywords" +
       "ON idCategories = categoryId WHERE keywords_name = :keyword LIMIT 1")
String findImagePathByKeyWordName(String keyword);

Upvotes: 1

Related Questions