简体   繁体   English

获取 Laravel 中的所有关系多对多多态

[英]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.从 Laravel v5.8.27 开始,有一种处理 eloquent 多态关系的方法。

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另见: https://laravel-news.com/laravel-5-8-27

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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