繁体   English   中英

删除记录前检查Laravel 8中是否存在hasMany关系

[英]Check if hasMany Relationship Exists in Laravel 8 Before Deleting Record

我试图在删除之前检查关系是否存在。 我在网上看到了很多关于此的其他帖子,但似乎无法让它发挥作用——当我点击删除时,它会忽略我的 @if 语句并删除记录。

型号/工作订单.php

...
public function continuations()
    {
        return $this->hasMany(Continuation::class);
    }
...

型号/续。php

...
public function workorder()
    {
        return $this->belongsTo(Workorder::class, 'workorder_id');
    }
...

工单/index.blade.php

...
  <td class="pr-6">
        <a wire:click="deleteWorkorder({{$workorder->id}})"
           role="menuitem">
        </a>
  </td>
...

工单/索引.php

...
public function deleteWorkorder($id)
    {
        $record = Workorder::find($id);
        $conExists = Continuation::where('workorder_id', $record->id)->exists();

        if($conExists){
            session()->flash('failed-message', 'You can\'t delete a workorder that has a Continuation');
            return;
        }
        $record->delete();
        session()->flash('success-message', 'Workorder Deleted Successfully');

    }
...

通过使用 isNotEmpty() 尝试类似的事情

$workorder= workorder::find($request->id);
            if ($workorder->continuations->isNotEmpty()) {
                return session()->flash('failed-message', 'You can\'t delete a workorder that has a Continuation');
            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM