Sunday, March 5, 2017

Defining Laravel relationship to inherited model

I am building an e-commerce app where I am tracking prices through multiple retailers. Here are my (simplified) database tables:

Products: id, name

Retailers: id, name

Offers: id, product_id(fk), retailer_id(fk), price

Here is my situation: Each retailer would have its own logic to hit its API and get the latest offers for products. Because of this, I would like to have Retailer as an abstract class where I could define something like:

abstract class Retailer extends Model {
  abstract protected function getOffer( $product_id );
}

class Amazon extends Retailer {
  protected function getOffer( $product_id ){
    // logic to hit Amazon's API
  }
}
class BestBuy extends Retailer { /* etc... */ }

then when I go through to update all of the product prices, I would like to do something like:

$products = Product::all();
foreach($products as $product){
  $product->retailer->getOffer($product_id);
}

where the retailer relationship actually returns an instance of Amazon or BestBuy, and not Retailer.

I took a look into Laravel's Polymorphic relationships, where I would store the retailer_id and retailer_type into the Offers table, but it seems to require creating tables for each of the child retailer classes, which doesn't really make sense in my case. I still feel like I could utilize the morph() functionality however.

Any idea how I could implement something like this, or another/better way I should approach this?

Thanks!



via Stetzon

Advertisement