From 6f7c65fab398820bc8e5026a5cb438e6f1ba2dfa Mon Sep 17 00:00:00 2001 From: Henrik Hautakoski Date: Fri, 23 Jul 2021 17:08:49 +0200 Subject: [PATCH] app/Models/Item.php: add reagent_for relationship. --- app/Models/Item.php | 9 +++++++++ tests/Feature/Models/ItemTest.php | 21 +++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/app/Models/Item.php b/app/Models/Item.php index 4008b55..2cdab40 100644 --- a/app/Models/Item.php +++ b/app/Models/Item.php @@ -47,6 +47,15 @@ class Item extends Model return $this->hasMany(Recipe::class); } + /** + * Get recipes that this item is reagent for. + */ + public function reagent_for() + { + return $this->belongsToMany(Recipe::class, 'reagents') + ->withPivot('quantity'); + } + public function getQuantityAttribute() { if ($this->pivot) { diff --git a/tests/Feature/Models/ItemTest.php b/tests/Feature/Models/ItemTest.php index dccee93..15fa64f 100644 --- a/tests/Feature/Models/ItemTest.php +++ b/tests/Feature/Models/ItemTest.php @@ -33,6 +33,27 @@ class ItemTest extends TestCase $this->assertEquals($recipe2->id, $item->recipes[1]->id); } + /** + * Test reagent for relationship. + * + * @return void + */ + public function test_reagent_for_relationship() + { + $item = Item::factory()->create(); + + $recipe = Recipe::factory() + ->hasAttached($item, ['quantity' => 1], 'reagents') + ->create(); + + $recipe2 = Recipe::factory() + ->hasAttached($item, ['quantity' => 1], 'reagents') + ->create(); + + $this->assertEquals($recipe->id, $item->reagent_for[0]->id); + $this->assertEquals($recipe2->id, $item->reagent_for[1]->id); + } + /** * Test quantity attribute *