本文介绍了在 Eloquent/Laravel 中选择所有者不是软删除的所有软删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询以获取所有软删除锦标赛:

I have a query to get all soft delete tournaments:

 $tournaments = Tournament::onlyTrashed();

Tournament 模型有一个 FK owner_id.

Thing is Tournament model has a FK owner_id.

有时,owner 已被软删除,因此当我尝试获取 $tournament->owner->id 时,会出现异常.

Sometimes, owner has been soft deleted, so when I try to get $tournament->owner->id, I get an exception.

如何在 Eloquent 中获取所有没有被软删除的用户的所有垃圾锦标赛???

How to get All trashed Tournament which user is not soft deleted in Eloquent???

是否有更优雅(雄辩)的解决方案:

Is there a more elegant (Eloquent) solution that :

 $tournaments = Tournament::onlyTrashed()
            ->join('users', 'users.id', '=', 'tournament.user_id')
            ->where('users.deleted_at', '=', null)
            ->select('tournament.*')
            ->get();

发送!

推荐答案

haswhereHas(用于更复杂的关系要求)可用于将结果限制为建立积极的关系.

has and whereHas (for more complex relationship requirements) can be used to limit results to records that have an active relationship.

Tournament::has('Owner')

将仅选择具有有效(现有且非软删除)所有者的锦标赛.

will select only tournaments with a valid (existing and non-soft-deleted) Owner.

这篇关于在 Eloquent/Laravel 中选择所有者不是软删除的所有软删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-10 09:20