public function load(Model $model)
{
$class_name = $this->class_name;
$this->set_keys(get_class($model));
// since through relationships depend on other relationships we can't do
// this initiailization in the constructor since the other relationship
// may not have been created yet and we only want this to run once
if (!isset($this->initialized)) {
if ($this->through) {
// verify through is a belongs_to or has_many for access of keys
if (!($through_relationship = $this->get_table()->get_relationship($this->through))) {
throw new HasManyThroughAssociationException("Could not find the association {$this->through} in model " . get_class($model));
}
if (!$through_relationship instanceof HasMany && !$through_relationship instanceof BelongsTo) {
throw new HasManyThroughAssociationException('has_many through can only use a belongs_to or has_many association');
}
// save old keys as we will be reseting them below for inner join convenience
$pk = $this->primary_key;
$fk = $this->foreign_key;
$this->set_keys($this->get_table()->class->getName(), true);
$class = $this->class_name;
$relation = $class::table()->get_relationship($this->through);
$through_table = $relation->get_table();
$this->options['joins'] = $this->construct_inner_join_sql($through_table, true);
// reset keys
$this->primary_key = $pk;
$this->foreign_key = $fk;
}
$this->initialized = true;
}
if (!($conditions = $this->create_conditions_from_keys($model, $this->foreign_key, $this->primary_key))) {
return null;
}
$options = $this->unset_non_finder_options($this->options);
$options['conditions'] = $conditions;
return $class_name::find($this->poly_relationship ? 'all' : 'first', $options);
}