如何在Laravel Eager加载中使用别名 [英] How to alias in Laravel Eager Loading

查看:769
本文介绍了如何在Laravel Eager加载中使用别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Laravel急切加载时使用别名:

I need to alias when I do a Laravel eager loading:

$posts = Post::with(array('images as main_image' => function($query) // do not run
            {
                $query->where('number', '=', '0');

            }))
            ->where('id', '=', $id)
            ->get();

return Response::json($posts);

我需要这样做,因为我想要这样的JSON响应:

I need to to this because I want the JSON response like this:

[
  {
    "id": 126,
    "slug": "abc",
    "name": "abc",
    "created_at": "2014-08-08 08:11:25",
    "updated_at": "2014-08-28 11:45:07",
    "**main_image**": [
      {
        "id": 223,
        "post_id": 126
        ...
      }
    ]
  }
]

有可能吗?

推荐答案

完美!你给我主意.终于,我做到了:

Perfect! you give me the idea. Finally I've done this:

Post.php

public function main_image()
{
    return $this->hasMany('FoodImage')->where('number','=','0');
}

public function gallery_images()
{
    // for code reuse
    return $this->main_image();
}

PostController.php

$posts = Post::with:with('main_image')->with('gallery_images')                    
            ->where('id', '=', $id)                    
            ->get();

这篇关于如何在Laravel Eager加载中使用别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆