官术网_书友最值得收藏!

Grabbing a list of data

We'll build a function that can provide a simple interface to get the data out of the system and to our controllers. So what do we want here? We want a simple function that is going to return an array of data (in our case, Polls). Of course, we'll also want to preload the Options for those Polls as well. The good news is that writing functions for our interfaces is just as simple as writing functions in Elixir! Let's take a look at our first example:

 def list_polls do
Repo.all(Poll) |> Repo.preload(:options)
end

All we've done here is written a single line of code, and yet this is also the code that will give us access to our Poll and Option data! Now, when we want a list of Polls, we don't need to think about having multiple schemas to interact with or multiple files to deal with; it's just one simple interface!

Okay, so we're talking a lot about how great it is that we've made this simple interface; let's actually put it into action! Before we move on any further, though, we should likely spend a few minutes talking about how to actually write queries in Ecto, as you may be doing quite a bit of that and it will be very important to understand exactly how to get data out of the database and into data structures that Elixir can properly interpret.

主站蜘蛛池模板: 沧源| 大同市| 包头市| 肃北| 合川市| 阿拉善左旗| 双桥区| 民乐县| 台江县| 贡山| 泰兴市| 饶平县| 阳东县| 宁德市| 胶州市| 新建县| 侯马市| 沙湾县| 靖安县| 江源县| 和静县| 荆门市| 沙坪坝区| 育儿| 枝江市| 竹溪县| 麻江县| 景洪市| 石嘴山市| 蓝山县| 中超| 贵州省| 凤台县| 宁乡县| 巴中市| 六枝特区| 得荣县| 商洛市| 大理市| 波密县| 张家港市|