2016-09-29 3 views
-2

두 가지 모델, 게임 및 이미지가 있습니다. 내 API에서 '/ games'를 쿼리하면 데이터베이스의 모든 게임에 대해 JSON을 반환합니다. GameController의 DB에 쿼리하여 게임 모델에 명시 적으로 "image_url"열을 만들지 않고 게임과 연결된 이미지를 전달할 수 있습니까? 그게 유일한 방법인가요? 나는이 같은 둥지 싶습니다 : 당신의 게임 모델에서중첩 된 JSON과의 다형성 관계가있는 Laravel REST API

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

답변

1

을이 같은 것을 쓸 필요 누군가가 발생하면

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

지금 확인하십시오. 알려 드리겠습니다. downvote보다는 대답 해 주셔서 감사합니다 :) – plushyObject

+0

이것은 내가 찾고있는 것과 아주 가깝습니다. 나는 Laravel 5에서 열망하는 로딩에 대한 더 많은 정보를 찾아 낼 수 있었고, 이것을 작동시킬 수있었습니다. 엄청 고마워! Laravel의 문서에서 확실히 잃어 버렸기 때문에 크게 환영 받았습니다 – plushyObject

0

: 당신이 게임을 할 때

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

을 그리고 이것을 찾으려면, 이것이 내가해야만했던 일입니다. 저는 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

이것은 열심히로드하는 것입니다, 참고로 – plushyObject

관련 문제