thybag/bonus-laravel-relations

为laravel提供额外的eloquent ORM关系类型。

0.2.3 2024-07-18 16:20 UTC

README

我最终需要的laravel eloquent ORM的一些额外奇怪而有趣的关系类型的选择。

其中许多都是实验性的,可能会以非预期和非标准的方式表现。

另一方面 - 它已测试过!
Build Status

所有内容均受MIT许可证的许可。

用法。

  1. 使用composer通过composer require thybag/bonus-laravel-relations进行安装
  2. use thybag\BonusLaravelRelations\Traits\BonusRelationsTrait;包含到您的模型中(或基模型,如果您希望它们在所有地方都可用。)
  3. 像使用任何其他关系一样使用这些关系。

如果您愿意,也可以单独添加关系特性。

关系

BelongsToMorph

获取单个类型的多态关系。

public function shop()
{
    return $this->belongsToMorph(Shop::class, 'noteable');
}

HasManyViaMany

通过无限数量的中间表定义一个关系。

public function products()
{
    return $this->hasManyViaMany(Product::class)->via(Shop::class)->via(Franchise::class);
}

HasAggregate

将聚合结果作为关系获取。这种方法的主要好处是它允许在集合上轻松地进行延迟加载此数据,并以更优雅的方式与结果交互。

public function productTotals()
{
    return $this->hasAggregate(Product::class)->selectRaw('
        COUNT(DISTINCT products.id) AS unique_products,
        SUM(products.amount) * AVG(products.value) AS stock_value,
        SUM(products.amount) AS total_products,
        AVG(products.value) AS average_product_value
    ');
}

HasMethod

将本地方法用作关系。

public function totalValue()
{
    return $this->hasMethod(function () {
        return ['total' => ($this->amount * $this->value)];
    });
}

BelongsToOne

通过枢纽表定义一对一关系。

public function latestRating()
{
    return $this->belongsToOne(Rating::class, 'shop_rating')->latest('created_at');
}