Laravel - 如何根据条件删除记录

时间:2021-02-17 09:49:52

标签: laravel

在我的 Laravel-5.8 中,我有这三 (3) 个模型:

参数

class Parameter extends Model
{    
    protected $table = 'parameters';
    protected $primaryKey = 'id';
    protected $fillable = [
                  'max_score',
                  'min_score',
                  'identity_id',
              ];

    public function identity()
    {
        return $this->belongsTo('App\Models\Identity','identity_id');
    }
}

身份

class Identity extends Model
{
    protected $table = 'identity';

    protected $fillable = [
              'id',
              'name',
          ];

    public function goals()
    {
       return $this->hasMany('App\Models\Goal');
    }  

    public function parameter()
    {
       return $this->hasOne(Parameter::class, 'identity_id');
    }    
}

目标

class Goal extends Model
{
    protected $table = 'goals';

    protected $fillable = [
                  'id',
                  'identity_id',
                  'title',
              ]; 

    public function identity()
    {
        return $this->belongsTo('App\Models\Identity','identity_id');
    }        
}

从模型来看,Identityidentity_id中有外键(Parameter),Identity在{{1}中有外键(identity_id) }}。

我在 Identity 中有这个控制器:

Goal

我希望用户根据以下条件删除 public function destroy($id) { try { $identity = Identity::findOrFail($id); $identity->delete(); Session::flash('success', 'Record deleted successfully.'); return redirect()->back(); } catch (Exception $exception) { Session::flash('error', 'Record delete failed!.'); return redirect()->back(); } } 记录:

  1. 当用户尝试删除 Identity 时,应用程序应检查 Identity 表并删除存在 Parameter 外键的记录。

  2. 其次,如果 identity_id 表中存在带有 identity_id 的记录,应用程序应该阻止删除。

如何调整 Goal 以实现这一目标?

2 个答案:

答案 0 :(得分:0)

你可以在你的“识别”模型中添加一个像“deleteAll()”这样的函数,并使用这样的关系删除参数:

class Identity extends Model
{
    protected $table = 'identity';

    protected $fillable = [
        'id',
        'name',
    ];

    public function goals()
    {
        return $this->hasMany('App\Models\Goal');
    }

    public function parameter()
    {
        return $this->hasOne(Parameter::class, 'identity_id');
    }

    public function deleteAll(){
        if(!$this->goals){
            $this->parameter->delete();
            return parent::delete();
        }
        return;
    }
}

答案 1 :(得分:0)

首先在 identity 中进行迁移,您需要这样做

$table->foreign('identity_id')->references('id')->on('parameters')->onDelete('cascade');

因此,当您删除 Identity 时,相关的 Parameter 将在数据库级别自动删除。 为防止删除(您提到的 2 种情况),您需要像这样检查

$identity = Identity::with('goals')->findOrFail($id);
if($identity->goals){
   // you can throw some error here
}