【问题标题】:How to delete hasMany relationship in Laravel without key如何在没有密钥的情况下删除 Laravel 中的 hasMany 关系
【发布时间】:2019-01-01 00:50:10
【问题描述】:

我正在尝试删除 hasMany 关系,但无济于事。

我有三个表:usersuser_detailsmanufacturers

UserhasOne user_details

user_details 属于user

manufacturers 有很多 usersuser_details

现在管理员删除manufacturer时,需要删除所有拥有该manufacturer_id的user_details和所有相关用户。

我的桌子:

用户:

id, unique_id, first_name, last_name, user_name, email, password, remember_token, created_at, updated_at, deleted_at

用户详细信息

id, user_id, avatar, locale, role_id, manufacturer_id, account_status, hospital_id, phone, city_id, created_at, updated_at, deleted_at

制造商

id, name, status, created_at, updated_at, deleted_at

我正在尝试这样做:

    /**
     * @return bool|null
     * @throws \Exception
     */
    public function softDelete()
    {
        $this->brand_presentations()->delete();
        $this->details()->delete();
        return parent::delete();
    }

这里有我的亲戚:

public function brand_presentations()
{
    return $this->hasMany(Brand_presentations::class, 'manufacturer_id', 'id')->withTrashed();
}

public function details()
{
   return $this->hasMany(User_details::class, 'manufacturer_id')->withTrashed();
}

这让我一直到user_details,但我无法获得用户。如何获取用户?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    如果我对您的理解正确,您需要遍历您的详细信息才能删除用户

    /**
     * @return bool|null
     * @throws \Exception
     */
    public function softDelete()
    {
        $this->brand_presentations()->delete();
        $details = $this->details
           foreach($details as $detail) {
              $user = detail->user
              // Delete or access user here
              $detail->delete()
           }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-02
      • 2016-04-16
      • 2014-07-28
      • 2010-09-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 2019-11-16
      相关资源
      最近更新 更多