laravel-5 - Laravel - 多对多多态关系

标签 laravel-5 eloquent polymorphism many-to-many relationship

我正在努力反对 Laravel 5.7 中的多态关系定义

数据情况如下: 我有一个用户模型、一个产品模型和一个销售模型 我基本上想为我的用户构建一个愿望 list ,它可以包含商品和产品,并且我希望在那里有一个多态关系,因为我必须添加新类型的东西来稍后出售。

在我的(简化的)当前数据模式中,我有

users
-email
-id

products
-id
-name

merchandises
-id
-name

还有臭名昭著的

wish_list_items
-user_id
-wish_list_item_type
-wish_list_id

就关系而言(针对用户):

public function wishListProducts()
{
    return $this->morphedByMany(Product::class, 'wish_list_items');
}

public function wishListMerchandises()
{
    return $this->morphedByMany(Merchandise::class, 'wish_list_items');
}

现在效果很好。但这对于我想要实现的目标来说还不够 - 我缺少的是获取愿望 list 中所有项目的步骤,无论其类型如何。目前:

public function wishListAll()
{
    return $this->load(['wishListProducts','wishListMerchandises']);
}

这显然给了我一个包含所有内容的列表,但在单独的集合中 - 我想要一个统一的集合。

第一个问题,有没有办法获取与该用户关联的所有内容,无论类型如何?它可能很简单,但我无法在任何地方找到它。

如果这是不可能的(我实际上怀疑 - 但这意味着这些多态关系只不过是避免创建另一个数据透视表的一种方法,我不介意这样做),人们会怎么想?最好的方法是什么? 最初的想法是创建一个接口(interface),我的所有可销售模型都将实现该接口(interface),以便统一所有内容 - 不过,我仍然必须循环遍历所有单独的集合,除非有一种简单的方法来合并它们,因为它们实现了相同的功能界面? 或者我应该为我的 WishListItems 定义一个模型(目前它是一个数据透视表,因此模型尚未定义),使我的所有可销售模型扩展 super 模型,并尝试将关系链接在一起?

感谢您的意见!

最佳答案

“默认”解决方案是合并两个(或多个)集合的访问器:

public function getWishListItemsAttribute()
{
    return $this->wishListProducts->toBase()->merge($this->wishListMerchandises);
}

// $user->wishListItems

+++ 更新+++

我创建了一个使用 View 合并关系的包:
https://github.com/staudenmeir/laravel-merged-relations

首先,在迁移中创建合并 View :

use Staudenmeir\LaravelMergedRelations\Facades\Schema;

Schema::createMergeView(
    'wish_list_items', [(new User)->wishListMerchandises(), (new User)->wishListProducts()]
);

然后定义关系:

class User extends Model
{
    use \Staudenmeir\LaravelMergedRelations\Eloquent\HasMergedRelationships;

    public function wishListItems()
    {
        return $this->mergedRelation('wish_list_items');
    }
}

像任何其他关系一样使用它:

$user->wishListItems;

$user->wishListItems()->paginate();

User::with('wishListItems')->get();

关于laravel-5 - Laravel - 多对多多态关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52877446/

相关文章:

laravel - 默认将值传递给@include

mysql - 使用 with() -laravel 4 时 Eloquent where 子句使用相关模型的列

php - Laravel 的 Eloquent ORM 与查询生成器

c++ - 如何在具有相同父类的两个类之间共享代码?

c++ - 函数是否可能只接受给定参数的一组有​​限类型?

php - 在 Laravel 5.2.37 中将信息从一个浏览器发送到另一个浏览器

php - Laravel 5.2 闪现消息不起作用

mysql - Eloquent 简化/组合查询

c++ - 在特定位置用元素填充数组

php - 每次刷新都会更改 Laravel session token