使用一对多关系时,是否可以控制子实体的顺序? [英] Is there a way to control the order of child entity, when using one-to-many relationhips?

查看:63
本文介绍了使用一对多关系时,是否可以控制子实体的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 https://developer.android.com/training/data-储物/房间/关系

我们可以建立一对多的关系

We can have one-to-many relationships

public class UserWithPlaylists {
    @Embedded public User user;
    @Relation(
         parentColumn = "userId",
         entityColumn = "userCreatorId"
    )
    public List<Playlist> playlists;
}

@Transaction
@Query("SELECT * FROM User")
public List<UserWithPlaylists> getUsersWithPlaylists();


在实体 User Playlist 中,我们添加了名为 sort_key


In both entity User and Playlist, we have added a column named sort_key

目的是,当我们执行查询时,我们可以执行以下操作

The purpose is, when we perform query, we can do the following

@Transaction
@Query("SELECT * FROM User order by sort_key")
public List<UserWithPlaylists> getUsersWithPlaylists();

我们可以控制 List< UserWithPlaylists> 的顺序.

但是, List< Playlist>怎么样?播放列表子实体?

我们如何为子实体 Playlist 定义自定义查询,以便我们可以控制 List< Playlist>播放列表排序?

How can we define a custom query for child entity Playlist, so that we can have control over List<Playlist> playlists ordering?

推荐答案

如何为子实体播放列表定义自定义查询,以便我们可以控制列表播放列表的排序?

How can we define a custom query for child entity Playlist, so that we can have control over List playlists ordering?

恐怕这里没有开箱即用的方式.

I'm afraid there is no out-of-box way here.

使用 @Relation 注释,您所拥有的就是:

Using @Relation annotation all you have is:

  • 5个注释的参数(associateBy 实体 entityColumn 父列投影.它们都不影响顺序子表的项目)

  • 5 annotation's parameters (associateBy, entity, entityColumn, parentColumn, projection. None of them has influence on order of child table's items)

关系部门内部,房间使用两个查询-首先,您明确地在DAO中编写

Under the Relation's hood Room uses two queries - first you explicitly write in your DAO

SELECT * FROM User order by sort_key

和另一个-用于从子表中获取数据(基于查询结果的类型和 @Relation 参数):

and another - for fetching data from the child table (based on type of query's result and on @Relation parameters):

SELECT * FROM PlayList WHERE userCreatorId IN (<List of users id from the first query>)

此查询是自动生成的,并且您的 @Relation 注释没有选项来更改项目的顺序.

This query is autogenerated and you @Relation annotation has no options to change item's order in it.

当然,获得此无序"结果后,您可以添加一些后处理以手动实现所需的功能

Of course, after getting this "unordered" result you can add some post-processing to achieve what you want manually

这篇关于使用一对多关系时,是否可以控制子实体的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆