如何在Laravel中删除无键的hasMany关系

时间:2018-07-24 11:53:19

标签: laravel

我试图删除hasMany关系,但无济于事。

我有三个表:usersuser_detailsmanufacturers

User hasOne user_details

user_details属于user

manufacturersusersuser_details

现在,当管理员删除制造商时,它需要删除拥有该制造商ID的所有user_details和所有相关用户。

我的桌子:

用户:

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

User_details

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,但无法获得用户。如何获得用户?

1 个答案:

答案 0 :(得分: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()
       }
}