I have a group model and I want to delete groups that don’t have any member.
How can I get empty groups with eloquent or SQL query ?
x
class Group extends Model
{
use HasFactory;
protected $fillable = [
'group_name',
'description'
];
public function users(){
return $this->hasMany(User::class);
}
}
And this is the User
model code:
class User extends Model implements AuthenticatableContract, AuthorizableContract
{
use SoftDeletes, Authenticatable, Authorizable, HasFactory, Notifiable;
public function getNameAttribute()
{
return $this->last_name.' '.$this->first_name;
}
public function group(){
return $this->belongsTo(Group::class);
}
}
Advertisement
Answer
I think whereDoesntHave
work in you situation.
Group::query()->whereDoesntHave('users')->delete();