【问题标题】:Adonis-Js : Get a specifc number of Entities in relationship with another EntityAdonis-Js:获取与另一个实体有关系的特定数量的实体
【发布时间】:2020-09-18 08:27:30
【问题描述】:

我需要您在 Adonis-Js 中帮助加载具有关系的实体。这是我的问题:

我有两个实体:

  • 联系人(属于联系人组)
  • 联系人组(有很多联系人)

我想请求获取 Contactgroup 列表,其中包含一些 Contact,这里是一个例子,这段代码给了我所有 Contactgroup 与所有与他们相关的联系人。 :

    let ContactgroupList = await Contactgroup.query()
        .where('profile_id', auth.user.id)
        .with('contact')
        .fetch();

在我的情况下,我只想获取所有 Contactgroup,其中只有一些 Contact 与他们相关(例如,最多 3 个 Contact每个 Contactgroup 找到),但是当我使用下面的代码时:

    let ContactgroupList = await Contactgroup.query()
        .where('profile_id', auth.user.id)
        .with('contact', (builder) => {
          builder.pick(3)
        })
        .fetch();

我只得到与第一个 Contactgroup 相关的前 3 个 contact,例如:

如果 Contactgroup[0] 有 X 个 Contact -> 它显示前 3 个 contact 的数组,并且 如果 Contactgroup[1] 有 X Contact -> 它将显示一个空数组。

如何为每个联系人组获得 3 个联系人

希望我的解释清楚,并提前感谢您的帮助!

【问题讨论】:

    标签: entity-relationship query-builder adonis.js lucid


    【解决方案1】:

    我的一个朋友使用 eagerLoadQuery 为我提供了解决方案:

    let ContactgroupList = await Contactgroup.query()
      .where('profile_id', auth.user.id)
      .with('contact', (builder) => {
        builder.eagerLoadQuery((relationQuery, foriegnKey, groups) => {
          relationQuery
            .from('contacts as c')
            .whereRaw('(select count(*) from `contacts` as c1 where c.contactgroup_id = c1.contactgroup_id AND c.id < c1.id) < 3')
            .whereIn(`c.${foriegnKey}`, groups)
            .orderBy('c.id', 'desc')
        })
      })
      .fetch()
    

    有关更多信息,另请参阅此帖子:Link

    【讨论】:

      猜你喜欢
      • 2016-01-13
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 2013-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多