【发布时间】:2021-02-17 09:49:52
【问题描述】:
在我的 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');
}
}
从模型来看,Identity 在Parameter 中有一个外键(identity_id),Identity 在Goal 中也有一个外键(identity_id)。
我在 Identity 中有这个控制器:
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();
}
}
我希望用户根据这些条件删除Identity记录:
-
当用户尝试删除
Identity时,应用程序应检查Parameter表并删除存在identity_id外键的记录。 -
其次,如果
Goal表中存在identity_id的记录,应用程序应该阻止删除。
如何调整public function destroy($id) 来实现这一点?
【问题讨论】:
-
您可以将这两个条件都放在数据库外键声明
ON DELERE CASCADE和ON DELETE RESTRICT中。如果您想在代码中使用它,请将您迄今为止尝试过的代码放入其中,以便我们帮助您了解哪些不起作用。 -
这是
atomic交易吗?即使有goal关系,也应该删除parameter关系?
标签: laravel