laravel - 调用数组上的成员函数 map()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51107262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel - Call to a member function map() on array
提问by gileneusz
I'm trying to make an array on my contact list, basing on my message table fromContact
relation:
我正在尝试根据我的消息表fromContact
关系在我的联系人列表中创建一个数组:
$messages = Message::where('offer_id', $id)->get();
$contacts = array();
foreach($messages as $message){
$contacts[] = $message->fromContact;
}
next I'm trying to make a map on contact, using $unreadIds that are result of other query on messages table:
接下来,我正在尝试使用 $unreadIds 制作联系人地图,这些 $unreadIds 是对消息表的其他查询的结果:
$contacts = $contacts->map(function($contact) use ($unreadIds) {
$contactUnread = $unreadIds->where('sender_id', $contact->id)->first();
$contact->unread = $contactUnread ? $contactUnread->messages_count : 0;
return $contact;
});
and this is not working... I've got simply message with error:
Call to a member function map() on array
这不起作用......我收到了一条简单的错误消息:
Call to a member function map() on array
and I understand it, I should not use map() on array - so I tried many ways to convert it to object - all failed.
我明白,我不应该在数组上使用 map() - 所以我尝试了很多方法将它转换为对象 - 都失败了。
for example converting contacts into object after array loop
例如在数组循环后将联系人转换为对象
$contacts = (object)$contacts;
gives error: "message": "Call to undefined method stdClass::map()",
给出错误: "message": "Call to undefined method stdClass::map()",
Maybe anyone knows how to fix that?
也许有人知道如何解决这个问题?
采纳答案by Marcus
Use laravel helper collect on the array then use map.
在数组上使用 laravel helper collect 然后使用 map。
$collection = collect($contacts);
$collection->map(function($contact) use ($unreadIds) {
$contactUnread = $unreadIds->where('sender_id', $contact->id)->first();
$contact->unread = $contactUnread ? $contactUnread->messages_count : 0;
return $contact;
});