From 01d3b4fd96cb9e6e5b2fa52a7de6067d90326dc4 Mon Sep 17 00:00:00 2001 From: Sam Minnee Date: Mon, 26 Aug 2019 18:06:50 +1200 Subject: [PATCH] FIX: Set many-many-through joinRecord on newly added records. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When many-many-through relations are queried, a joinRecord is set on each DataObject in the list to provide the extra fields defined on the connector object. This didn’t previously happen when the record was first add()ed to a list. This fixes that bug. --- src/ORM/ManyManyThroughList.php | 5 +++++ tests/php/ORM/ManyManyThroughListTest.php | 9 +++++++++ 2 files changed, 14 insertions(+) diff --git a/src/ORM/ManyManyThroughList.php b/src/ORM/ManyManyThroughList.php index 738ff913e..93160703a 100644 --- a/src/ORM/ManyManyThroughList.php +++ b/src/ORM/ManyManyThroughList.php @@ -217,6 +217,11 @@ class ManyManyThroughList extends RelationList $record = $hasManyList->createDataObject($extraFields ?: []); $record->$localKey = $itemID; $hasManyList->add($record); + + // Link the join object to the $item, as if it were queried from within this list + if ($item instanceof DataObject) { + $item->setJoin($record, $this->manipulator->getJoinAlias()); + } } /** diff --git a/tests/php/ORM/ManyManyThroughListTest.php b/tests/php/ORM/ManyManyThroughListTest.php index 0b18cbec5..6a6b83318 100644 --- a/tests/php/ORM/ManyManyThroughListTest.php +++ b/tests/php/ORM/ManyManyThroughListTest.php @@ -6,6 +6,7 @@ use SilverStripe\Core\Config\Config; use SilverStripe\Dev\SapphireTest; use SilverStripe\ORM\DataObject; use SilverStripe\ORM\ManyManyThroughList; +use SilverStripe\ORM\Tests\ManyManyThroughListTest\Item; use SilverStripe\ORM\Tests\ManyManyThroughListTest\PolyItem; use SilverStripe\ORM\Tests\ManyManyThroughListTest\PolyJoinObject; use SilverStripe\ORM\Tests\ManyManyThroughListTest\Locale; @@ -75,6 +76,14 @@ class ManyManyThroughListTest extends SapphireTest $this->assertNotNull($item2->getJoin()); $this->assertEquals('join 2', $item2->getJoin()->Title); $this->assertEquals('join 2', $item2->ManyManyThroughListTest_JoinObject->Title); + + // Check that the join record is set for new records added + $item3 = new Item; + $this->assertNull($item3->getJoin()); + $parent->Items()->add($item3); + $expectedJoinObject = ManyManyThroughListTest\JoinObject::get()->filter(['ParentID' => $parent->ID, 'ChildID' => $item3->ID ])->first(); + $this->assertEquals($expectedJoinObject->ID, $item3->getJoin()->ID); + $this->assertEquals(get_class($expectedJoinObject), get_class($item3->getJoin())); } /**