ddzobov/laravel-pivot-softdeletes

让您的 Eloquent 模型的关联关系能够在 Laravel/Lumen 中实现软删除

2.2.0 2024-07-15 12:32 UTC

This package is auto-updated.

Last update: 2024-09-15 13:09:06 UTC


README

安装

使用 composer 安装此包

composer require ddzobov/laravel-pivot-softdeletes

基本用法

use DDZobov\PivotSoftDeletes\Model;

class Post extends Model
{
    public function tags()
    {
        return $this->belongsToMany(Tag::class)->withSoftDeletes();
    }
}

class Tag extends Model
{
    public function posts()
    {
        return $this->belongsToMany(Post::class)->withSoftDeletes();
    }
}

自定义关联模型

use DDZobov\PivotSoftDeletes\Model;
use DDZobov\PivotSoftDeletes\Relations\Pivot;

class Post extends Model
{
    public function tagsWithCustomPivot()
    {
        return $this->belongsToMany(Tag::class)->using(PostTag::class)->withSoftDeletes();
    }
}

class Tag extends Model
{
    public function postsWithCustomPivot()
    {
        return $this->belongsToMany(Post::class)->using(PostTag::class)->withSoftDeletes();
    }
}

class PostTag extends Pivot
{
    
}

自定义 deleted_at 字段

$this->belongsToMany(Post::class)->withSoftDeletes('custom_deleted_at');

显示未删除的(默认行为)

// withoutTrashed() already called inside withSoftDeletes()
$this->belongsToMany(Post::class)->withSoftDeletes();

// same behavior
$this->belongsToMany(Post::class)->withSoftDeletes()->withoutTrashedPivots();

显示存在和已删除的

$this->belongsToMany(Post::class)->withSoftDeletes()->withTrashedPivots();

只显示已删除的

$this->belongsToMany(Post::class)->withSoftDeletes()->onlyTrashedPivots();

恢复关联记录

$post->tags()->restore([$tag->id]);

恢复关联记录(使用自定义关联模型)

$post->tagsWithCustomPivot()->restore([$tag->id]);

强制解除关联记录

$post->tags()->forceDetach([$tag->id]);

与强制解除关联记录同步

$post->tags()->syncWithForceDetaching([$tag->id]);

测试

composer test

许可证

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