在 Ecto 模型中使用外键查询

Query with foreign keys in Ecto Models

我有以下 Ecto 模式:

schema "videos" do
    field :name, :string
    field :mpdName, :string
    field :urlPlayready, :string, size: 500
    field :urlWidevine, :string, size: 500
    field :urlFile, :string, size: 500
    field :custom_data, :string, size: 500
    field :drm_today, :boolean
    field :vote, :integer
    has_many :user_videos, VideoBackend.UserVideos
    has_many :users, through: [:user_videos, :user]
    timestamps
  end


schema "users"  do
   field :name, :string
   field :email, :string ,  [:primary_key]
   field :encrypted_password, :string
   field :password, :string, virtual: true
   has_many :user_videos, VideoBackend.UserVideos
   has_many :videos, through: [:user_videos, :video]
   timestamps   
end

schema "user_videos" do
  belongs_to :users, VideoBackend.User
  belongs_to :videos, VideoBackend.Video
  field :time, :float
  field :device, :integer
  timestamps
end

现在我想查询 select user_videos 给定特定的 "user" 和特定的 "video"。在 SQL 我会写这个简单的查询:

SELECT FROM user_videos WHERE user = "user" and video = "video"

我尝试编写以下 Ecto 查询,但它不起作用:

def single_userVideo(user,video) do
    from u in UserVideos,
    where: u.user == ^user and u.video == ^video
end

你知道我怎么解决吗?

如果您正在使用 has_manybelongs_to,那么您可能希望根据 _id 列进行查询。

所以 SQL 将是:

SELECT FROM user_videos WHERE user_id = "user" and video_id = "video"

以及查询:

def single_user_video(%{id: user_id}, %{id: video_id}) do
  from u in UserVideos,
  where: u.user_id == ^user_id,
  where: u.video_id == ^video_id
end

如果在查询中多次使用 where/3,它将在查询中使用 AND

where expressions are used to filter the result set. If there is more than one where expression, they are combined with an and operator. All where expressions have to evaluate to a boolean value.

顺便说一句,Elxir 中的函数是用 snake_case 编写的,所以 single_userVideos 应该是 single_user_videos