2017-05-03 59 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; 
}