本文介绍了Laravel仅在不存在相关模型的情况下删除模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有一个名为"manufacturer"的模型,该模型与另一种"vehicle"模型具有一对多的关系.现在,我不想让用户删除制造商,如果有任何与此型号相关的车辆.

Lets say i have a model called 'manufacturer' and this model has one to many relation with another model 'vehicle'. Now i dont want to let users delete a manufacturer if there are any vehicles associated with this model.

//In Manufacturer model

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

在存储库/控制器中,我还有另一种检查方法.

And in the repository/controller i have another method to check for it.

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

这确实会输出所有关联车辆的制造商数据.但这效率不高,所以我只想检查一下是否还有一辆车,就不要删除制造商.

推荐答案

我相信您想使用has方法来确保制造商拥有某些车辆.

I believe you'd want to use the has method to make sure the manufacture has some vehicles.

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

然后,您只需要确保!is_null($manufacture)

这篇关于Laravel仅在不存在相关模型的情况下删除模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 12:38