Laravel only delete a model if no related model exist

大城市里の小女人 提交于 2020-01-04 05:42:16

问题


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();
}

This does outputs the manufacturer data with all the associated vehicles. but this is not efficient, so i just want to check that if there is even one vehicle then dont delete the manufacturer.


回答1:


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

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

Then you'd just want to make sure !is_null($manufacture)




回答2:


As you have a vehicles() method in your Manufacturer model, you may just do this:

Use the whereDoesntHave method to filter all Manufacturers without vehicles before deleting them:

Manufacturer::whereDoesntHave('vehicles')->get();

From the API:

Add a relationship count condition to the query with where clauses.




回答3:


You can return the count of total vehicles like this:

  return [
      'count' => Manufacturer::with('vehicles')->find($id)->count()
  ];

Now you can just check the count.




回答4:


This will return boolean on whether there is an vehicles on the manufacturer.

return (Manufacturer::with([
    'vehicles'=> function($query){
        return $query->limit(1);
    }])->find($id)->vehicles);

You can add foreign key and prima key on the vehicles to reduce the number of column being query for performance concern.

return $query->limit(1)->select('id','manufacturer_id');


来源:https://stackoverflow.com/questions/34136141/laravel-only-delete-a-model-if-no-related-model-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!