简体   繁体   中英

3 (optional) levels of relationships in Eloquent

I want to create a website where dog owners can search for what they can feed their dogs safely. Or not.
I've been struggling with the conceptuality of this one a bit, bear with me...

Let's take four example products (table products):

  1. Avocado
  2. Chocolate
  3. Chicken
  4. Carrot
  5. ...

These products can have one or more elements (table elements):

  1. Pit
  2. Meat
  3. Skin
  4. Bones
  5. ...

And these elements can be prepared differently (table attributes):

  1. Raw
  2. Cooked
  3. ...

Now let's link these up...

  1. An avocado contains a pit, has skin and meat
  2. Chocolate is simply chocolate
  3. Chicken has meat and contains bones. Meat and bones can be raw and cooked

And now I need to say something about these products and their elements/ preparation...

  1. An avocado (1) pit (1.1) and skin (1.3) are toxic to dogs, its meat is good (no matter what, 1.2)
  2. Chocolate is always toxic (2)
  3. Chicken meat (3.2) is always good, its bones cooked (3.4.2) are toxic, raw (3.4.1) is good.
  4. A carrot (4) is always good

To me, it seems like I have to store these relations (no matter their depth) in a table and have a separate table that says whether that relationship is safe or toxic.

But I'm unsure how to set this up in Laravel Models and query it via Eloquent. Because on the user side you want to search for chocolate or avocado only and see the various relations returned.

I propose to make such a structure

products

  • id
  • name

product_elements

  • id
  • product_id
  • name
  • preparation (raw, cooked)
  • is_toxic
class Product extends Model
{
    protected $guarded = ['id'];

    public function elements()
    {
        return $this->hasMany(ProductElement::class);
    }
}

class ProductElement extends Model
{
    protected $guarded = ['id'];

    public function product()
    {
        return $this->belongsTo(Product::class);
    }
}

when the user has selected food and wants to see what the dog can eat

ProductElement::query()->whereIn('product_id', [1, 2])->get();
ProductElement::query()->whereIn('product_id', [1, 2])->where('is_toxic', false)->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM