mlezcano1985/laravel-pivot-soft-deletes

使用Laravel SoftDeletes特性对Eloquent关联模型进行软删除。

1.0.0 2017-12-11 15:42 UTC

This package is auto-updated.

Last update: 2024-09-29 04:37:12 UTC


README

此项目不再受支持,请考虑使用其他包。

Laravel PHP框架的Pivot软删除

使用Laravel SoftDeletes特性软删除Eloquent关联模型的简单快捷方式。

安装

此特性通过Composer安装。要安装,只需将其添加到您的composer.json文件中

$ composer require mlezcano1985/laravel-pivot-soft-deletes

示例

在多对多模型中包含SoftDeletes和PivotSoftDeletes。

<?php
namespace App;

use Mlezcano1985\Database\Support\PivotSoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;

class Account extends Authenticatable
{
    use Notifiable, SoftDeletes, PivotSoftDeletes;

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];
    }

    /**
     * @return BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

    /**
     * Automatically creates hash for the user password.
     *
     * @param  string $value
     * @return void
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }
}

<?php
namespace App;

use Mlezcano1985\Database\Support\PivotSoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    use SoftDeletes, PivotSoftDeletes;

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];
    }

    /**
     * @return BelongsToMany
     */
    public function accounts()
    {
        return $this->belongsToMany(Account::class);
    }
}

现在我们可以使用Account模型的detach()方法来软删除关联表

$account = App\Role::find($role_id)->accounts()->findOrFail($account_id)
$account->detach(); // Soft delete the Intermediate Table

定义自定义中间表模型

如果我们想定义一个自定义中间表模型,过程与上面相同。例如

/**
 * @return BelongsToMany
 */
public function roles()
{
    return $this->belongsToMany(Role::class)->using(AccountRole::class);
}

但是强烈建议在自定义中间表模型上包含SoftDeletes特性

<?php
namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Database\Eloquent\SoftDeletes;

class AccountRole extends Pivot
{
    use SoftDeletes;

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];
    }
}

现在

$account = App\Role::find($role_id)->accounts()->findOrFail($account_id)
$account->detach(); // Soft delete the Intermediate Table

支持

如果您在此包中遇到一般问题,请随时通过Twitter联系我。

如果您认为您发现了一个问题,请使用GitHub问题跟踪器报告,或者更好的是,fork仓库并提交一个pull request。

如果您在使用此包,我很想听听您的想法。谢谢!