首页 > 解决方案 > 为什么在 foreach 集合时未定义属性?

问题描述

$conversations = Conversations::with('bulletin', 'messages')->leftJoin('own', 'conversations.bulletin_id', '=',
    'own.id')
    ->select('conversations.*')
    ->where('owner_id', $userId)
    ->orWhere('owner', $userId)
    ->orderBy('updated_at', 'desc')
    ->get();
dd($conversations);

$conversation = Conversations::getInfo($conversations->first());

foreach ($conversations as $conversation) {
    dd($conversation->bulletin);
}

https://i.imgur.com/qne8Xhh.png - 带有第一个 dd() 的屏幕截图

https://i.imgur.com/OCjFfD0.png - foreach() 中的屏幕截图 dd() - 这里没有

如果我尝试访问$conversation->bulletin->id这将是错误“未定义的属性...”

public static function getInfo($conversation)
{
    $conversation->messages = self::find($conversation->id)->messages();
    $conversation->bulletin = self::find($conversation->id)->bulletin();
    $conversation->users = self::find($conversation->id)->users();

    return $conversation;
}

标签: laravelrelationship

解决方案


发生这种情况是因为对于某些$conversations人或可能是其中之一$conversation没有任何bulletin. 结果,当您遍历所有$conversations并访问$conversion->bulletin->id该文件时,conversation会导致错误。当你运行dd它时,只转储第一个conversation然后死掉。结果,您没有正确看到问题所在。

替换以下行:

dd($conversation->bulletin);

用这条线,看看:

dump($conversation->id, $conversation->bulletin);

我很确定你会看到至少有一个对话没有任何公告。

更新:

self::find($conversation->id)->users(); 将返回关系对象,而不是用户的集合。如果您想访问用户集合,那么您应该这样做self::find($conversation->id)->usersbulletin和_messages

实际上,我认为您不需要这种getInfo()方法。你只需要with正确使用查询的方法,

所以,替换:

Conversations::with('bulletin','messages')

这部分由Conversations::with('bulletin','messages',用户)


推荐阅读