diff --git a/src/Model/Product.php b/src/Model/Product.php index d44271b..746a4bd 100644 --- a/src/Model/Product.php +++ b/src/Model/Product.php @@ -448,4 +448,19 @@ public function tags(): BelongsToMany 'term_taxonomy_id' ); } + + /** + * Get the related vendors. + * + * @return BelongsToMany + */ + public function vendor() + { + return $this->belongsToMany( + Vendor::class, + 'term_relationships', + 'object_id', + 'term_taxonomy_id' + ); + } } diff --git a/src/Model/Vendor.php b/src/Model/Vendor.php new file mode 100644 index 0000000..ce617ee --- /dev/null +++ b/src/Model/Vendor.php @@ -0,0 +1,27 @@ +createProduct(); + $vendorName = 'vendor name'; + $vendorTerm = (new TermFactory())->create(['name' => $vendorName]); + $vendorTax = Vendor::factory()->create(['term_id' => $vendorTerm->term_id]); + + DB::table('term_relationships')->insert([ + 'object_id' => $product->ID, + 'term_taxonomy_id' => $vendorTax->term_taxonomy_id, + 'term_order' => 0, + ]); + + $this->assertModelExists($product->vendor->first()); + $this->assertSame($product->vendor->first()->name, $vendorName); + } + + private function createProduct(): Product + { + /** @var Product */ + $product = Product::factory()->create(); + + return $product; + } +} diff --git a/tests/database/factories/TermFactory.php b/tests/database/factories/TermFactory.php new file mode 100644 index 0000000..6995792 --- /dev/null +++ b/tests/database/factories/TermFactory.php @@ -0,0 +1,29 @@ + + */ +class TermFactory extends Factory +{ + protected $model = Term::class; + + /** + * Define the model's default state. + * + * @return array + */ + public function definition() + { + return [ + 'name' => $this->faker->name + ]; + } +} diff --git a/tests/database/factories/VendorFactory.php b/tests/database/factories/VendorFactory.php new file mode 100644 index 0000000..5b10d3a --- /dev/null +++ b/tests/database/factories/VendorFactory.php @@ -0,0 +1,29 @@ + + */ +class VendorFactory extends Factory +{ + protected $model = Vendor::class; + + /** + * Define the model's default state. + * + * @return array + */ + public function definition() + { + return [ + 'taxonomy' => 'wcpv_product_vendors', + 'description' => '', + ]; + } +}