laravel - 为什么在 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;
}
解决方案
发生这种情况是因为对于某些$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)->users
。bulletin
和_messages
实际上,我认为您不需要这种getInfo()
方法。你只需要with
正确使用查询的方法,
所以,替换:
Conversations::with('bulletin','messages')
这部分由Conversations::with('bulletin','messages',
用户)
推荐阅读
- csv - 写入 csv 文件
- javascript - 在 API 错误上打破 Vuex Action 中的 Promise
- azure - 我不小心更改了Azure windows vm的IP适配器,导致无法远程连接到服务器
- shopify - 使用 Algolia 的 named_tags 在 Shopify 上存在分层方面的问题
- python-3.x - Jinja2 - 循环使用十六进制数字作为键的字典时出现问题
- .net-core - “错误无法创建 'AppDbContext' 类型的对象。对于设计时支持的不同模式”
- python - 从python调用时如何使用awk?
- python - 需要安装多个 Python 吗?
- android - How do I set the initialRoute for Android in Flutter?
- javascript - 使用 DataTable.js 的 js 源数据的单个列搜索过滤器,顶部有过滤器