php - 如果不存在相关模型,Laravel 只会删除模型

标签 php laravel laravel-5 eloquent

假设我有一个名为“制造商”的模型,该模型与另一个模型“车辆”具有一对多关系。现在,如果有任何车辆与该模型关联,我不想让用户删除制造商。

//In Manufacturer model

public function vehicles()
{
    return $this->hasMany('Vehicle');
}

在存储库/ Controller 中,我有另一种方法来检查它。

public function checkAssociatedVehicles($id)
{
    return Manufacturer::with('vehicles')->find($id)->toJson();
}

这会输出所有相关车辆的制造商数据。但这效率不高,所以我只想检查是否只有一辆车,然后不要删除制造商。

最佳答案

我相信您会想要使用 has 方法来确保制造商有一些车辆。

$manufacture = Manufacturer::has('vehicles')->find($id);

那么你只想确保 !is_null($manufacture)

关于php - 如果不存在相关模型,Laravel 只会删除模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34136141/

相关文章:

php - Laravel 5.1 播种新专栏

php - Laravel Eloquent,如何用公式定义表关系?

php - PDO 的行数

php - 为什么代码进入无限循环? (

php - Wordpress(自定义主题)不会在 MAC 浏览器上滚动?

php - 如何格式化(转换)laravel 数据库分页结果?

php - 在 CodeIgniter 的 Active Record 中使用 'having'

javascript - 如何使用 Vue 禁用表单提交时的 window.onbeforeunload ?

javascript - TypedJS 错误 : Uncaught ReferenceError: Typed is not defined

symfony - 通过 Symfony 组件使用 unoconv 将 DOC 转换为 PDF