簡體   English   中英

laravel - 在數組上調用成員函數map()

[英]laravel - Call to a member function map() on array

我正在嘗試在我的聯系人列表上創建一個數組,基於我的消息表fromContact relation:

    $messages = Message::where('offer_id', $id)->get();
    $contacts = array();
    foreach($messages as $message){
      $contacts[] = $message->fromContact;
    }

接下來,我正在嘗試使用$ unrereadIds創建聯系人地圖,這是對消息表的其他查詢的結果:

    $contacts = $contacts->map(function($contact) use ($unreadIds) {
        $contactUnread = $unreadIds->where('sender_id', $contact->id)->first();
        $contact->unread = $contactUnread ? $contactUnread->messages_count : 0;
        return $contact;
    });

這不起作用...我只是帶錯誤的消息: Call to a member function map() on array

我理解它,我不應該在數組上使用map() - 所以我嘗試了很多方法將它轉換為對象 - 都失敗了。

例如,在數組循環后將聯系人轉換為對象

 $contacts = (object)$contacts;

給出錯誤: "message": "Call to undefined method stdClass::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;
});

https://laravel.com/docs/5.6/collections

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM