简体   繁体   中英

Get all relations in Laravel many to many Polymorphic

I've four tables:

products:
 - id
 - name

promotions:
 - id
 - name

selections:
 - id
 - name

selectionable:
 - id
 - selection_id
 - selectionable_id
 - selectionable_type

Each selection can contains either products or promotions (with polymorphic many to many). For example:

Selection: "Best Seller This Month"
Contains:  4 products

Selection: "Starter Pack For Beginners"
Contains:  12 promotions

I've tried some but None of this worked: But it's what I expect to see in output:

Selection::with('selectionable')->findOrFail($id);
// It's a selection which contains some products
{
  name: "Starter Pack For Beginners",
  selectionable: [
     {
        id: 2,
        name: "product test"
     },
     {
        id: 241,
        name: "product foo"
     },
     {
        id: 98,
        name: "product bar"
     },  
  ]
}

Is there any idea to do this in clean and optimal way?

Starting from Laravel v5.8.27 there is a method for working with eloquent polymorphic relationships.

The query you need is something like this:

Selectionable::whereHasMorph('selectionable', [Product::class, Promotion::class], function ($query) {
    $query->where('title', 'foo');
})->get();

See also: https://laravel-news.com/laravel-5-8-27

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