带嵌套JSON多态关系的Laravel REST API
问题描述:
我有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'
}
}
答
在你的游戏模式,你需要写的东西是这样的:
public function images()
{
return $this->hasMany('App\Images', 'imageable_id', 'id')
->whereImageableType('App\Game');
}
而当你把你的游戏:
return Games::select()
->with('images')
->get();
答
如果有人碰巧找到这个,这是我最终不得不做的。我正在使用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
现在检查了这一点。我会让你知道的。谢谢你的回答,而不是downvote :) – plushyObject
这非常接近我正在寻找的东西。我能够在Laravel 5中找到更多有关急切加载的信息,并使其工作。万分感谢!它绝对迷失在Laravel的文档中,所以非常感谢 – plushyObject