Trong Rails, nếu tôi có các thiết lập sau:Trộn Phạm vi và hiệp hội ở Phoenix/Ecto
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
def self.approved
where(approved: true)
end
end
Sau đó, tôi có thể làm một cái gì đó như thế này:
post = Post.find(100)
comments = post.comments.approved
để nhanh chóng có được tất cả các ý kiến đã được phê duyệt cho số Post
đã cho.
Tôi có thể làm điều gì đó tương tự trong Ecto?
defmodule MyApp.Post do
use Ecto.Model
schema "posts" do
#columns omitted
has_many :comments, MyApp.Comment
end
end
defmodule MyApp.Comment do
use Ecto.Model
schema "comments" do
#columns omitted
belongs_to :post, MyApp.Post
end
end
tôi đã có post
với comments
được nạp sẵn:
post = MyApp.Post
|> MyApp.Repo.get(100)
|> MyApp.Repo.preload(:comments)
Tôi thậm chí không chắc chắn bắt đầu từ đâu với phạm vi approved
trong MyApp.Comment
.
bài viết trên blog này có thể chỉ cho bạn đi đúng hướng: http://blog.drewolson.org/composable-queries-ecto/ – Gazler