fidum/laravel-eloquent-morph-to-one

为 Laravel eloquent 添加 MorphToOne 关系

2.4.0 2024-03-13 13:42 UTC

This package is auto-updated.

Last update: 2024-09-13 14:54:59 UTC


README

Latest Version on Packagist GitHub Workflow Status (with branch) Codecov Twitter Follow

📣 向 Ankur Kumar 致敬,他在这包 Eloquent Relations 中编写了这个关系的原始代码。由于我需要对其进行一些调整以适应我的需求,所以我创建了此包。🙌

安装

您可以通过 composer 安装此包

composer require fidum/laravel-eloquent-morph-to-one

用法

MorphToOne 关系底层使用 Laravel 的 MorphToMany。然而,不同之处在于它返回 一个 模型,而不是模型的 Collection

如果数据库中没有相关模型,它将返回 null,而 MorphToMany 将返回一个空的 Collection

示例

<?php

namespace App;

use Fidum\EloquentMorphToOne\HasMorphToOne;
use Fidum\EloquentMorphToOne\MorphToOne;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany;

class Post extends Model
{
    use HasMorphToOne;

    public function featuredImage(): MorphToOne
    {
        return $this->morphToOne(Image::class, 'imageable')
            ->wherePivot('featured', 1);
            //->withDefault();
    }
    
    public function images(): MorphToMany
    {
        return $this->morphToMany(Image::class, 'imageable')
            ->withPivot('featured');
    }

}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany;

class Image extends Model
{
    public function posts(): MorphToMany
    {
        return $this->morphedByMany(Post::class, 'imageable');
    }

    public function videos(): MorphToMany
    {
        return $this->morphedByMany(Video::class, 'imageable');
    }
}

现在您可以像这样访问关系

<?php

// eager loading
$post = Post::with('featuredImage')->first();
dump($post->featuredImage);
// lazy loading
$post->load('featuredImage');

更新关系时,首选使用 sync 而不是 save

$post->featuredImage()->sync([Image::find(123)]);
$post->featuredImage()->sync([Image::find(456)]);
$post->images->count(); // 1 row :)

❌ 不要使用 save,因为它会遵循 morphToMany 的行为,而不是更新现有内容。

$post->featuredImage()->save(Image::find(123));
$post->featuredImage()->save(Image::find(456));
$post->images->count(); // 2 rows :(

测试

composer test

变更日志

请参阅 CHANGELOG 了解最近更改的详细信息。

贡献

请参阅 CONTRIBUTING 了解详情。

安全

如果您发现任何安全问题,请通过电子邮件 fidum.dev@gmail.com 而不是使用问题跟踪器。

鸣谢

许可

MIT 许可证(MIT)。请参阅 许可文件 了解更多信息。