我正在开发一个 Jmeter 板,用户可以创建互联网提供商,然后他可以将数据包与之关联。问题是,如果用户在关联的internet提供商之后删除,当我转到数据包时,网页会崩溃,因为它试图访问不存在的internet提供商。因此,我想防止如果在另一个表中引用internet提供商1次或多次,则用户无法删除它。
internet提供商删除功能:
public function destroy(Internet $provider)
{
$oldName = $provider->name;
$oldUrlFoto = $provider->image_url;
try {
Storage::delete('public/provider/' . $oldUrlFoto);
$provider->delete();
return redirect()->route('admin.providers')
->with('alert-msg', 'The provider "' . $provider->name . '" was deleted!')
->with('alert-type', 'success');
} catch (\Throwable $th) {
// $th é a exceção lançada pelo sistema - por norma, erro ocorre no servidor BD MySQL
// Descomentar a próxima linha para verificar qual a informação que a exceção tem
if ($th->errorInfo[1] == 1451) { // 1451 - MySQL Error number for "Cannot delete or update a parent row: a foreign key constraint fails (%s)"
return redirect()->route('admin.providers')
->with('alert-msg', 'We cant delete this provider "' . $oldName . '", because its already in use!')
->with('alert-type', 'danger');
} else {
return redirect()->route('admin.providers')
->with('alert-msg', 'We cant delete this provider "' . $oldName . '". Error: ' . $th->errorInfo[2])
->with('alert-type', 'danger');
}
}
}
数据包模型和互联网提供商模型:
class Packets extends Model
{
use HasFactory, SoftDeletes;
protected $fillable = ['internet_provider_id', 'name', 'price'];
public function internetProvider()
{
return $this->belongsTo(Internet::class, 'internet_provider_id');
}
}
class Internet extends Model
{
use HasFactory, SoftDeletes;
protected $fillable = ['name', 'image_url'];
public function packets()
{
return $this->hasMany(Packets::class);
}
}
迁移:
Schema::create('internet', function (Blueprint $table) {
$table->bigInteger('id')->unsigned()->autoIncrement();
$table->string('name', 50);
$table->string('image_url');
$table->timestamps();
// Clientes podem ser apagados com "soft deletes"
$table->softDeletes();
});
Schema::create('packets', function (Blueprint $table) {
$table->bigInteger('id')->unsigned()->autoIncrement();
$table->bigInteger('internet_provider_id')->unsigned();
$table->foreign('internet_provider_id')->references('id')->on('providers');
$table->string('name');
$table->string('price');
$table->timestamps();
$table->softDeletes();
});
暂无答案!
目前还没有任何答案,快来回答吧!