2016-09-29 39 views
-2

我有2個模型,遊戲和圖像。當我在API中查詢「/遊戲」時,我將爲數據庫中的所有遊戲返回JSON。我應該如何在GamesController中查詢數據庫以傳遞與遊戲相關的圖像,而不在我的遊戲模型中顯式創建「image_url」列?這是唯一的方法嗎?我想窩這樣的:帶嵌套JSON多態關係的Laravel REST API

{ 
id: 1, 
title: 'Halo 5', 
image: { 
     url: 'http://theimageurlhere.com', 
     imageable_id: 1, 
     imageable_type: 'App\Game' 
    } 
} 

回答

1

在你的遊戲模式,你需要寫的東西是這樣的:

public function images() 
{ 
    return $this->hasMany('App\Images', 'imageable_id', 'id') 
     ->whereImageableType('App\Game'); 
} 

而當你把你的遊戲:

return Games::select() 
     ->with('images') 
     ->get(); 
+0

現在檢查了這一點。我會讓你知道的。謝謝你的回答,而不是downvote :) – plushyObject

+0

這非常接近我正在尋找的東西。我能夠在Laravel 5中找到更多有關急切加載的信息,並使其工作。萬分感謝!它絕對迷失在Laravel的文檔中,所以非常感謝 – plushyObject

0

如果有人碰巧找到這個,這是我最終不得不做的。我正在使用Laravel 5.3:

/*Game Model*/ 

public function images() 
{ 
    return $this->morphMany('App\Image', 'imageable'); 
} 

/*Image Model*/ 

public function imageable() 
{ 
    return $this->morphTo(); 
} 

/*Games Controller*/ 

public function index() 
{ 
    $games = Game::with('images')->get(); 

    return $games; 
} 

===================================== 
Here is the JSON it returns: 
{ 
    id: 1, 
    title: "As she said to.", 
    slug: "as-she-said-to", 
    description: "Consequatur at qui iusto.", 
    created_at: "2016-09-29 12:04:36", 
    updated_at: "2016-09-29 12:04:36", 
    images: [ 
     { 
      id: 1, 
      url: "http://www.mobygames.com/images/covers/l/281002-rayman-legends-xbox-one-front-cover.png", 
      imageable_id: 1, 
      imageable_type: "App\Game", 
      created_at: "2016-09-29 12:04:36", 
      updated_at: "2016-09-29 12:04:36" 
     } 
     ] 
    } 

======================================== 
Then in my Vue.js front-end: 

<img v-bind:src="game.images[0].url" class="img-responsive"/> 
+0

這被稱爲熱切加載,FYI – plushyObject