如何在不预加载的情况下加载关联?

时间:2016-01-18 21:36:09

标签: elixir ecto

我有以下两种模式:

<?php
$handle = fsockopen("google.com", 80);
if ($handle) {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: google.com\r\n";
    $out .= "Connection: Keep-Alive\r\n\r\n";
    fwrite($handle, $out);

    $bytesread = 0;
    while (($buffer = fgets($handle, 4096)) !== false) {
        if(strpos($buffer, "Content-Length:") !== false) {
                list(, $len) = explode("Content-Length: ", $buffer);
        }

        if($buffer === "\r\n") {
                break;
        }
    }

    $data = '';
    while($bytesread != intval($len)) {
        $buf = fgets($handle, 1024);
        $bytesread += strlen($buf);
        $data .= $buf;
    }
    fclose($handle);
    print $data;
}
?>

schema "users" do
    field :email, :string
    field :crypted_password, :string
    field :password, :string, virtual: true

    has_many :exercise_entries, ExerciseEntry

    timestamps
end

我在iex中运行了以下代码:

schema "exercise_entries" do
  field :date, Ecto.DateTime
  field :exercise, :string
  field :category, :string
  field :weight, :float
  field :reps, :integer
  belongs_to :user, User

  timestamps
end

我知道我可以u = Repo.get(User, 1) iex(8)> u.exercise_entries #Ecto.Association.NotLoaded<association :exercise_entries is not loaded> 然后我可以访问exercise_entries。是否有可能以某种方式加载exercise_entries而不先预加载它们?

1 个答案:

答案 0 :(得分:3)

Ecto需要执行另一个数据库查询来获取练习条目。这将是正常的Repo.all查询,但您可以使用Ecto.assoc

而不是手动构建它
ee = Repo.all(Ecto.assoc(u, :exercise_entries))