如何排除具有软删除连接 table 关联的预加载
How can I exclude preloads with soft deleted join table associations
使用 Elixir,Ecto.Query,Postgres
我通过联接 table UserLocation
在 User
和 Location
之间建立了关联。我使用 deleted_at
作为软删除并在查询时检查 is_nil(ul.deleted_at)
。
如果我软删除连接 table 记录,我将拥有
%User{id: 1, name: "larskris", deleted_at: nil, location: #Ecto.Association.NotLoaded<association :location is not loaded>}
%UserLocation{id: 25, user_id: 1, location_id: 13, deleted_at: #DateTime<2018-01-17 18:01:45Z>}
%Location{id: 13, address: "Some street", deleted_at: nil}
我如何 运行 一个 Ecto 查询来阻止这些 "deleted" 位置的预加载?
Repo.one(
from u in User,
left_join: ul in UserLocation, on: a.id == ul.activity_id and is_nil(ul.deleted_at),
left_join: l in Location, on: ul.location_id == l.id and is_nil(l.deleted_at),
where: u.id == ^user_id
and is_nil(u.deleted_at),
preload: [:location]
)
以上returns用户还预加载了本应为nil的位置。即使没有关联的位置,我也总是想要用户。
到目前为止我尝试过的所有操作都会预加载软删除的位置
单独查询位置和用户,然后映射它们以构建我需要的东西,但并不理想。
使用内置关联还 returns 软删除位置。
这可能只是使用 preload
来使用 LEFT JOIN 的问题(我认为您给定的语法会自行进行全新的预加载)。
from u in User,
left_join: ul in UserLocation, on: a.id == ul.activity_id and is_nil(ul.deleted_at),
left_join: l in Location, on: ul.location_id == l.id and is_nil(l.deleted_at),
where: u.id == ^user_id and is_nil(u.deleted_at),
preload: [location: l]
有关详细信息,请参阅 Ecto docs for preload()。
使用 Elixir,Ecto.Query,Postgres
我通过联接 table UserLocation
在 User
和 Location
之间建立了关联。我使用 deleted_at
作为软删除并在查询时检查 is_nil(ul.deleted_at)
。
如果我软删除连接 table 记录,我将拥有
%User{id: 1, name: "larskris", deleted_at: nil, location: #Ecto.Association.NotLoaded<association :location is not loaded>}
%UserLocation{id: 25, user_id: 1, location_id: 13, deleted_at: #DateTime<2018-01-17 18:01:45Z>}
%Location{id: 13, address: "Some street", deleted_at: nil}
我如何 运行 一个 Ecto 查询来阻止这些 "deleted" 位置的预加载?
Repo.one(
from u in User,
left_join: ul in UserLocation, on: a.id == ul.activity_id and is_nil(ul.deleted_at),
left_join: l in Location, on: ul.location_id == l.id and is_nil(l.deleted_at),
where: u.id == ^user_id
and is_nil(u.deleted_at),
preload: [:location]
)
以上returns用户还预加载了本应为nil的位置。即使没有关联的位置,我也总是想要用户。
到目前为止我尝试过的所有操作都会预加载软删除的位置
单独查询位置和用户,然后映射它们以构建我需要的东西,但并不理想。
使用内置关联还 returns 软删除位置。
这可能只是使用 preload
来使用 LEFT JOIN 的问题(我认为您给定的语法会自行进行全新的预加载)。
from u in User,
left_join: ul in UserLocation, on: a.id == ul.activity_id and is_nil(ul.deleted_at),
left_join: l in Location, on: ul.location_id == l.id and is_nil(l.deleted_at),
where: u.id == ^user_id and is_nil(u.deleted_at),
preload: [location: l]
有关详细信息,请参阅 Ecto docs for preload()。