如何查询Ecto关联中的第三个关系 [英] How to query a third relation in Ecto Associations

查看:88
本文介绍了如何查询Ecto关联中的第三个关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Snapmail
|> preload(:user)
|> preload(:snapmail_cameras)
|> preload([snapmail_cameras: :camera])
|> preload([snapmail_cameras: [camera: :vendor_model]])
|> preload([snapmail_cameras: [camera: [vendor_model: :vendor]]])
|> Repo.all

我在Ecto中有上述查询。在这。每个 snapmail 都有一个 snapmail_camera ,而 snapmail_camera 有一个 camera_id (是相机的 id (来自相机表)。

I have above query in Ecto. in this. Each snapmail has a snapmail_camera and snapmail_camerahas a camera_id which is camera's id (from camera table.)

和相机表的字段为 status

我试图仅获取那些快照邮件,其中其 snapmail_cameras 的相机状态不等于 project_finished

I am trying to get only those snapmails where its snapmail_cameras's camera's status is not equal to project_finished

这是 snapmail snapmail_camera

belongs_to :user, User, foreign_key: :user_id
has_many :snapmail_cameras, SnapmailCamera

任何帮助都将非常感激。我如何获得那些 snapmails

any help would be so thankful. How I can get those snapmails?

推荐答案

您正在预加载吨,这将为您提供大量数据,您可以在代码中过滤我们的数据,但是如果您使用 join / 5

You're preloading a ton, which will get you lots of data you could filter our in code, but the database can return much less data if you use join/5:

假设我已经解释了您的方案正确,这就是我的工作。

Assuming I've interpreted your scheme correctly, here's what I'd do.

import Ecto.Query

query =
  from s in MyApp.Snapmail,
  join: sc in assoc(s, :snapmail_cameras),
  join: c in assoc(sc, :camera),
  where: c.status != ^"status_finished"

MyApp.Repo.all(query)

这只会返回 Snapmails 而没有所有这些预加载,但是您始终可以添加`preload / 3'在查询结束时将数据导入。

This will only return Snapmails without all those preloads, but you can always add a `preload/3' at the end of your query to bring that data in.

这篇关于如何查询Ecto关联中的第三个关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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