使用Ecto

时间:2019-01-10 14:34:03

标签: postgresql elixir phoenix-framework ecto

我有3种型号:

user.ex

  schema "users" do 
    ...
    many_to_many(:acts, Act, join_through: UserAct)
  end

act.ex

  schema "acts" do
    ...
    many_to_many(:users, User, join_through: UserAct)
  end

user_act.ex

  schema "users_acts" do
    belongs_to :user, User
    belongs_to :act, Act
  end

每次删除UserAct时,我都要检查是否有孤立的Act模型并在事务中将其删除。

在SQL中看起来像这样

DELETE FROM acts WHERE NOT EXISTS (
  SELECT 1 FROM users_acts ua WHERE ua.act_id = acts.id
);

or 

DELETE FROM acts WHERE id NOT IN (SELECT act_id FROM users_acts);

我的问题是如何使用Ecto编写类似的查询?

请显示所有已知的方法:连接,片段等...

2 个答案:

答案 0 :(得分:0)

一种解决方案是使用片段。

Repo.delete_all(
  from a in Act,
  where: fragment("? NOT IN (SELECT act_id FROM users_acts)", a.id)
)

答案 1 :(得分:0)

使用联接:

import pandas as pd
import requests

df = pd.DataFrame({'image_url':['https://dcist.com/wp-content/uploads/sites/3/2020/02/wilford_newsletter.jpg'], 'about':['a cat']})

# Use df.iloc[0] to pull the first image url, and requests to download the data for the image
a = plt.imread(requests.get(df.iloc[0]['image_url'], stream=True).raw, format='jpeg')

plt.imshow(a)
plt.show()