Laravel - 如果不存在关系则删除

Moh*_*mad 4 laravel laravel-5

以下是该模型之一.我想删除Telco条目只有在没有其他模型引用它的情况下?什么是最好的方法?

namespace App;

use Illuminate\Database\Eloquent\Model;

class Telco extends Model
{
    public function operators()
    {
        return $this->hasMany('App\Operator');
    }

    public function packages()
    {
        return $this->hasMany('App\Package');
    }

    public function topups()
    {
        return $this->hasMany('App\Topup');
    }

    public function users()
    {
        return $this->morphMany('App\User', 'owner');
    }

    public function subscribers()
    {
        return $this->hasManyThrough('App\Subscriber', 'App\Operator');
    }
}
Run Code Online (Sandbox Code Playgroud)

cha*_*fdo 9

您可以使用deleting模型事件并在删除之前检查是否有任何相关记录,并防止删除(如果存在).

在你的Telco模型中

protected static function boot()
{
    parent::boot();

    static::deleting(function($telco) {
        $relationMethods = ['operators', 'packages', 'topups', 'users'];

        foreach ($relationMethods as $relationMethod) {
            if ($telco->$relationMethod()->count() > 0) {
                return false;
            }
        }
    });
}
Run Code Online (Sandbox Code Playgroud)