我有一个名为GroupService的模型,它与Service有关联。如果GroupService与Service有关联,我希望在删除GroupService时阻止或限制。如果GroupService没有关联,则用户可以删除它。我一直在遵循这些指南,但这些指南不适用:
[1][Laravel - How to prevent delete when there is dependent field](https://stackoverflow.com/questions/60578308/laravel-how-to-prevent-delete-when-there-is-dependent-field)
[2][https://laracasts.com/discuss/channels/laravel/how-to-prevent-the-delete-of-table-row-that-has-its-id-in-another-table](https://laracasts.com/discuss/channels/laravel/how-to-prevent-the-delete-of-table-row-that-has-its-id-in-another-table)
下面是我的代码:
模型组服务:
class GroupService extends Model
{
use HasFactory;
protected $table = 't_grup_layanan';
protected $guarded = ['id'];
// protected $fillable = [
// 'bisnis_id',
// 'deskripsi'
// ];
protected $with = ['business'];
public function service(){
return $this->hasMany(Service::class);
}
public function business(){
return $this->belongsTo(Business::class, 'bisnis_id');
}
// protected static function boot(){
// parent::boot();
// static::deleting(function($groupservice) {
// $relationMethods = ['service'];
// foreach ($relationMethods as $relationMethod) {
// if ($groupservice->$relationMethod()->count() > 0) {
// return false;
// }
// }
// });
// }
}
模型服务:
class Service extends Model
{
use HasFactory;
protected $table = 't_layanan';
protected $guarded = ['id'];
// protected $fillable = [
// 'gruplayanan_id',
// 'nama',
// 'deskripsi'
// ];
protected $with = ['groupservice'];
public function groupservice(){
return $this->belongsTo(GroupService::class, 'gruplayanan_id');
}
}
控制器组服务:
public function destroy(GroupService $groupservice, $id)
{
$groupService = GroupService::find(Crypt::decrypt($id));
if ($groupService->service()->exists())
{
abort('Resource cannot be deleted due to existence of related resources.');
}
$groupService->delete();
return redirect('/dashboard/gruplayanan/')->with('danger', 'Data dihapus !');
}
迁移组服务:
public function up()
{
Schema::create('t_grup_layanan', function (Blueprint $table) {
$table->id();
$table->foreignId('bisnis_id')->nullable()->index('fk_bisnis_to_group');
$table->text('deskripsi');
$table->timestamps();
});
}
迁移服务:
public function up()
{
Schema::create('t_layanan', function (Blueprint $table) {
$table->id();
$table->foreignId('gruplayanan_id')->index('fk_grup_to_layanan');
$table->text('nama');
$table->text('deskripsi');
$table->timestamps();
});
}
public function up()
{
Schema::table('t_layanan', function (Blueprint $table) {
$table->foreign('gruplayanan_id', 'fk_grup_to_layanan')->references('id')->on('t_grup_layanan')->onUpdate('CASCADE')->onDelete('CASCADE');
});
}
1条答案
按热度按时间fdbelqdn1#
我觉得问题就在这里,在你们的关系功能上:
根据Laravel约定,Eloquent将采用表名父模型并以
_id
作为后缀。因此,它在
t_layanan
表中查找当前不存在的t_grup_layanan_id
字段。因此,如果您想覆盖默认约定,则必须在第二个参数上指定它,如下所示。