2017-05-03 23 views
0

我有一個名爲images的belongsToMany關係的BlogPost模型,此關係使用鏈接表將博客帖子ID與圖像ID相關聯。Laravel keyBy - 從鏈接表中排序結果

當數據拉動了一篇博客文章,圖像屬性看起來是這樣的:

[images] => Array 
      (
       [0] => Array 
        (
         [id] => 8304 
         [original] => /img/blog/2017/5/wifiradio_original_59089cae673db.png 
         [large] => /img/blog/2017/5/wifiradio_large_59089cae673db.jpg 
         [medium] => /img/blog/2017/5/wifiradio_medium_59089cae673db.jpg 
         [small] => /img/blog/2017/5/wifiradio_small_59089cae673db.jpg 
         [name] => wifiradio.png 
         [alt] => wifiradio.png 
         [created_at] => 2017-05-02 14:50:22 
         [updated_at] => 2017-05-02 14:50:22 
         [pivot] => Array 
          (
           [blog_post_id] => 47749 
           [image_id] => 8304 
           [id] => 136949 
           [type] => featured 
          ) 

        ) 

      ) 

    ) 

數組鍵是不是數值有用,我想數組鍵是價值pivot->類型。

Laravels keyBy方法幾乎做我需要的東西,但我無法直接對返回的數據進行操作。

是否可以在模型中使用keyBy,以便數據總是以可用格式返回?

回答

0

我通過格式化控制器中的數組解決了這個問題。 這裏是我創建的功能,如果任何人有類似的問題:

public function formatPosts($posts){ 
    foreach($posts as $post){ 
     $images = collect($post->images); 
     unset($post->images); 
     $post->images = $images->keyBy('pivot.type'); 
    } 
    return $posts; 
}