From c5522f0ff6cdee080f88a89ce1fdcb3e43811e18 Mon Sep 17 00:00:00 2001 From: Christian Haschek Date: Mon, 31 Mar 2025 22:08:37 +0200 Subject: [PATCH 1/2] fixing wrong-key-association bug --- lib/Relationship/HasAndBelongsToMany.php | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/lib/Relationship/HasAndBelongsToMany.php b/lib/Relationship/HasAndBelongsToMany.php index ff20dfde..3a007fcd 100644 --- a/lib/Relationship/HasAndBelongsToMany.php +++ b/lib/Relationship/HasAndBelongsToMany.php @@ -42,14 +42,21 @@ 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); + + // 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'] + ]); return $rel->to_a(); } From 9ca63b0e1e144fb345b8a32b03769d7906f2dcf6 Mon Sep 17 00:00:00 2001 From: Christian Haschek Date: Mon, 31 Mar 2025 22:27:46 +0200 Subject: [PATCH 2/2] fixing stan errors --- lib/Relationship/HasAndBelongsToMany.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/Relationship/HasAndBelongsToMany.php b/lib/Relationship/HasAndBelongsToMany.php index 3a007fcd..65eff851 100644 --- a/lib/Relationship/HasAndBelongsToMany.php +++ b/lib/Relationship/HasAndBelongsToMany.php @@ -58,7 +58,9 @@ public function load(Model $model): mixed ' ON ' . $associated_table . '.' . $associated_pk . ' = ' . $join_table . '.' . $this->options['association_foreign_key'] ]); - return $rel->to_a(); + $results = $rel->to_a(); + /** @var list $results */ + return $results; } public static function inferJoiningTableName(string $class_name, string $association_name): string