diff --git a/lib/Relationship/HasAndBelongsToMany.php b/lib/Relationship/HasAndBelongsToMany.php index ff20dfde..65eff851 100644 --- a/lib/Relationship/HasAndBelongsToMany.php +++ b/lib/Relationship/HasAndBelongsToMany.php @@ -42,16 +42,25 @@ public function is_poly(): bool */ public function load(Model $model): mixed { - /** - * @var Relation - */ $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 $results */ + return $results; } public static function inferJoiningTableName(string $class_name, string $association_name): string