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

时间:2017-09-04 09:11:13

标签: 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');
    }
}

3 个答案:

答案 0 :(得分:8)

您可以使用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;
            }
        }
    });
}

答案 1 :(得分:1)

在这里看到答案后,我不会感觉到将static function boot粘贴复制到每个需要它的模型上。因此,我制作了一个名为trait的{​​{1}}。我将@chanafdo的SecureDelete放在foreach中的public function内。

这样,我可以将其重用于需要它的模型。

SecureDelete

SecureDelete.php

trait SecureDelete { /** * Delete only when there is no reference to other models. * * @param array $relations * @return response */ public function secureDelete(String ...$relations) { $hasRelation = false; foreach ($relations as $relation) { if ($this->$relation()->withTrashed()->count()) { $hasRelation = true; break; } } if ($hasRelation) { $this->delete(); } else { $this->forceDelete(); } } } 添加到需要它的模型中。

use SecureDelete

use Illuminate\Database\Eloquent\Model; use App\Traits\SecureDelete; class Telco extends Model { use SecureDelete; public function operators() { return $this->hasMany('App\Operator'); } // other eloquent relationships (packages, topups, etc) }

TelcoController.php

此外,除了public function destroy(Telco $telco) { return $telco->secureDelete('operators', 'packages', 'topups'); } 以外,您还可以制作一个扩展Trait的自定义模型,例如BaseModel.php,在其中放置Illuminate\Database\Eloquent\Model,并将模型更改为{ {1}}。

答案 2 :(得分:0)

$relationships = array('operators', 'packages', 'topups', 'users', 'subscribers');

$telco = Telco::find($id);
$should_delete = true;

foreach($relationships as $r) {
    if ($telco->$r->isNotEmpty()) {
        $should_delete = false;
        break;
    }
}

if ($should_delete == true) {
    $telco->delete();
}

嗯,我知道这很难看,但我认为它应该有效。如果你不喜欢这个,只需调用每个关系属性并检查它是否返回一个空集合(意味着没有关系)

如果所有关系都为空,则删除!