【问题标题】:Delete unused groups in Laravel 8删除 Laravel 8 中未使用的组
【发布时间】:2021-06-06 10:53:11
【问题描述】:

我有一个组模型,我想删除没有任何成员的组。

如何通过 eloquent 或 SQL 查询获得空组?

class Group extends Model
{
    use HasFactory;
    protected $fillable = [
        'group_name',
        'description'
    ];

    public function users(){
        return $this->hasMany(User::class);
    }
}

这是User 型号代码:

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

【问题讨论】:

    标签: sql laravel eloquent


    【解决方案1】:

    你可以使用whereDoesntHave:

    Group::whereDoesntHave('users')->delete();
    

    您可以通过运行以下语句来确保删除正确的组:

    dump(Group::whereDoesntHave('users')->get());
    

    【讨论】:

      【解决方案2】:

      我认为whereDoesntHave 适合你的情况。

       Group::query()->whereDoesntHave('users')->delete();
      

      【讨论】:

        猜你喜欢
        • 2021-03-13
        • 2022-01-22
        • 2021-06-26
        • 2021-11-08
        • 2022-01-21
        • 2022-01-21
        • 2021-08-02
        • 2022-01-05
        • 2021-05-31
        相关资源
        最近更新 更多