Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 17 additions & 8 deletions lib/Relationship/HasAndBelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,25 @@ public function is_poly(): bool
*/
public function load(Model $model): mixed
{
/**
* @var Relation<TModel>
*/
$rel = new Relation($this->class_name, [], []);
$rel->from($this->attribute_name);
$other_table = Table::load(get_class($model))->table;
$rel->where($other_table . '. ' . $this->options['foreign_key'] . ' = ?', $model->{$model->get_primary_key()});
$rel->joins([$other_table]);
// Use the join table rather than the attribute name.
$join_table = $this->options['join_table'];
$rel->from($join_table);

return $rel->to_a();
// Filter on the join table's column that references the parent model.
$rel->where($join_table . '.' . $this->options['foreign_key'] . ' = ?', $model->{$model->get_primary_key()});

// Now join the associated table using its actual primary key.
$associated_table = Table::load($this->class_name)->table;
$associated_pk = Table::load($this->class_name)->pk[0];
$rel->joins([
'INNER JOIN ' . $associated_table .
' ON ' . $associated_table . '.' . $associated_pk . ' = ' . $join_table . '.' . $this->options['association_foreign_key']
]);

$results = $rel->to_a();
/** @var list<TModel> $results */
return $results;
}

public static function inferJoiningTableName(string $class_name, string $association_name): string
Expand Down
Loading