2014-08-28 134 views
3

我需要别名的时候我做了Laravel预先加载:如何别名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 
     ... 
     } 
    ] 
    } 
] 

有可能的?

回答

1

我不认为你可以用Eloquent做到这一点,但可能会有一些解决方法可行。

如果您使用的是PHP 5.6,则可以使用该函数进行别名。

use function images as main_image; 

如果您使用的PHP版本小于,你可以创建一个main_image()功能,并调用它images()

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

完美!你给我这个主意。最后,我已经做到了这一点:

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(); 
+1

你可以用一个单一的与'后写查询::与(” main_image','gallery_image')' – Needpoule 2014-08-29 09:02:48

+0

完美!谢谢 – kurtko 2014-08-30 12:19:07