【问题标题】:Laravel Property [nameOfProperty] does not exist on this collection instance此集合实例上不存在 Laravel 属性 [nameOfProperty]
【发布时间】:2019-04-08 22:11:17
【问题描述】:

我在 Laravel 中获取用户及其关系;比赛结果。

$user = User::where('id', Auth::user()->id)->with('competitionResults')->get();

我现在想检查竞争结果是否为空,因为它返回此错误:此集合实例上不存在属性 [competitionsResults]。

我试过了

if ($user->competitionResults()->exists()) {...}

if ($user->competitionResults()->isNotEmpty()) {...}

if (count($user->competitionResults)) {...}

但它们都返回相同的错误。

如何检查关系数据是否为空?

【问题讨论】:

    标签: relationship is-empty laravel-5.7


    【解决方案1】:

    您正在检查该属性是否存在于 集合 中,而不是模型中。使用 first() 而不是 get() 来返回 User 类的实例。

    【讨论】:

    • Thomas 是正确的,您在用户模型上使用 get() 会返回一组用户
    猜你喜欢
    • 2020-07-11
    • 2019-07-10
    • 2021-07-23
    • 2021-09-07
    • 2023-03-12
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多