我有一个类似follower
设置的Twitter,其中Users
可以通过connection
模型互相关注。在user#show
我要显示最新的5 followers
和followees
。我不知道给定connections
user
有多少Repo.preload
我想将inserted_at
限制为最新的Connection
。
我正在努力使用Ecto来加载最新的connections
模型中的followers
followees
[...]
def show(conn, %{"id" => id}) do
user =
Repo.get!(User, id)
|> Repo.preload([:followers, :followees])
[...]
defmodule MyApp.User do
use MyApp.Web, :model
schema "users" do
[...]
has_many :follower_connections, MyApp.Connection, foreign_key: :followee_id
has_many :followers, through: [:follower_connections, :follower]
has_many :followee_connections, MyApp.Connection, foreign_key: :follower_id
has_many :followees, through: [:followee_connections, :followee]
[...]
和defmodule MyApp.Connection do
use MyApp.Web, :model
schema "connections" do
belongs_to :follower, MyApp.User
belongs_to :followee, MyApp.User
[...]
。什么是最干净,最高效的方式?
网络/控制器/ user_controller.ex
$(document).ready(function() {
$('#example'String).DataTable( {
dom: 'Bfrtip'String,
buttons: [
{
extend: 'excelFlash'String,
filename: 'Data export'String
},
{
extend: 'pdfFlash'String,
filename: 'Data export'String
}
]
});
});
网络/模型/ user.ex
{{1}}
网络/模型/ connection.ex
{{1}}
答案 0 :(得分:1)
我无法在预加载:followers
或:followees
时找到直接进行此操作的方法,但我通过直接与:follower_connections
和:followee_connections
进行交互找到了一种方法。
defmodule MyApp.Connection do
...
def latest(n) do
Ecto.Query.from(u in MyApp.Connection, order_by: [desc: :inserted_at], limit: ^n)
end
end
两个用户都有1
和2
,并且两者之间都有关注者/关注者连接,
Repo.get(User, 1) |>
Repo.preload(followee_connections: {Connection.latest(5), [:followee]},
follower_connections: {Connection.latest(5), [:follower]})
运行查询
[debug] SELECT u0。“id”,u0。“name”,u0。“inserted_at”,u0。“updated_at” FROM“users”AS u0 WHERE(u0。“id”=?)[1] OK query = 0.6ms
[debug] SELECT c0。“id”,c0。“follower_id”,c0。“followee_id”, c0。“inserted_at”,c0。“updated_at”FROM“connections”AS c0 WHERE (c0。“follower_id”IN(?))ORDER BY c0。“follower_id”,c0。“inserted_at” DESC限制? [1,5] OK查询= 0.4ms
[debug] SELECT u0。“id”,u0。“name”,u0。“inserted_at”,u0。“updated_at” FROM“users”AS u0 WHERE(u0。“id”IN(?))[2] OK query = 0.3ms 排队= 0.1ms的
[debug] SELECT c0。“id”,c0。“follower_id”,c0。“followee_id”, c0。“inserted_at”,c0。“updated_at”FROM“connections”AS c0 WHERE (c0。“followee_id”IN(?))ORDER BY c0。“followee_id”,c0。“inserted_at” DESC限制? [1,5] OK查询= 0.4ms
[debug] SELECT u0。“id”,u0。“name”,u0。“inserted_at”,u0。“updated_at” FROM“users”AS u0 WHERE(u0。“id”IN(?))[2] OK query = 0.4ms 排队= 0.1ms的
对我来说效率很高(如果预加载需要在另一个查询中发生;否则一些JOIN可能会更快)。
唯一的问题是,您无法直接在:followers
上访问:followees
或User
,而只能通过所有.follower
和{{1}中的.follower_connections
所有.followee
。
这是使用上述查询返回的结构:
.followee_connections