2014-08-28 132 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