Laravel only delete a model if no related model ex

2019-07-09 05:39发布

问题:

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');