本文介绍了与条件的ecto关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个模型,分别是PostComment,注释模型可以是normalfancy这两种类型中的一种,由comments列中的type定义.桌子.

现在我想在我的Post模型上添加2个关联,其中1个引用花哨的注释,而1个引用普通的注释,我该怎么做?所以我想要这样的东西:

has_many :fancy_comments, MyApp.Comment, where: [type: 0]
has_many :normal_comments, MyApp.Comment, where: [type: 1]
解决方案

在ecto中不可用,在.

您可以为此使用可组合查询:

defmodule MyApp.Comment do

  ...schema, etc.

  def fancy(query) do
    from c in query,
      where: type == 0
  end

  def normal(query) do
    from c in query,
      where: type == 1
  end    
end

然后您可以使用has_many :comments, MyApp.Comment并基于该查询:

assoc(post, :comments) |> Comment.fancy() |> Repo.all()

这是有关可组合查询的博客文章.

您还可以在查询中使用预加载:

fancy_query = from(c in Comments, where: type == 0)
Repo.preload(post, comments: fancy_query)

Let's say I have two models, Post and Comment and the comment model can be 1 out of 2 types, normal and fancy which is defined by the column type in the comments table.

Now I want to add 2 associations on my Post model, where one refers to fancy comments and one to normal ones, how would I do it? So I want something like this:

has_many :fancy_comments, MyApp.Comment, where: [type: 0]
has_many :normal_comments, MyApp.Comment, where: [type: 1]
解决方案

This is not available in Ecto, there is a lengthy discussion about it on this GitHub issue.

You could use a composable query for this:

defmodule MyApp.Comment do

  ...schema, etc.

  def fancy(query) do
    from c in query,
      where: type == 0
  end

  def normal(query) do
    from c in query,
      where: type == 1
  end    
end

You can then use has_many :comments, MyApp.Comment and query based on that:

assoc(post, :comments) |> Comment.fancy() |> Repo.all()

Here is a blog post about composable queries.

You can also use a preload with a query:

fancy_query = from(c in Comments, where: type == 0)
Repo.preload(post, comments: fancy_query)

这篇关于与条件的ecto关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 16:19