【问题标题】:How to alias in Laravel Eager Loading如何在 Laravel Eager Loading 中使用别名
【发布时间】:2014-10-22 08:36:30
【问题描述】:

我在执行 Laravel 预加载时需要别名:

$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 响应:

[
  {
    "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
        ...
      }
    ]
  }
]

有可能吗?

【问题讨论】:

    标签: laravel eloquent eager-loading


    【解决方案1】:

    完美!你给我的想法。最后我做到了:

    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('main_image', 'gallery_images')                    
                ->where('id', '=', $id)                    
                ->get();
    

    【讨论】:

    • 你可以用Post::with('main_image','gallery_image')写你的查询
    【解决方案2】:

    我认为 Eloquent 无法做到这一点,但有一些变通方法可能会奏效。

    如果您使用的是 PHP 5.6,则可以为函数设置别名。

    use function images as main_image;
    

    如果您使用的 PHP 版本低于该版本,您可以创建一个 main_image() 函数并让它调用 images()

    public function main_image()
    {
        return $this->images();
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-17
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      • 2017-08-19
      相关资源
      最近更新 更多