【问题标题】:Laravel REST API with Polymorphic Relationship with nested JSON具有嵌套 JSON 的多态关系的 Laravel REST API
【发布时间】:2016-09-29 06:53:37
【问题描述】:

我有 2 个模型,游戏和图像。当我在我的 API 中查询“/games”时,我将返回数据库中所有游戏的 JSON。我应该如何在我的 GamesController 中查询数据库以传递与游戏关联的图像而不在我的游戏模型中显式创建“image_url”列?这是唯一的方法吗?我想这样嵌套:

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

【问题讨论】:

    标签: php rest laravel vue.js


    【解决方案1】:

    在您的游戏模型中,您需要编写如下内容:

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

    当你玩游戏时:

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

    【讨论】:

    • 现在检查一下。我会让你知道。感谢您的回答,而不是投反对票:)
    • 这非常接近我想要的。我能够在 Laravel 5 中找到有关急切加载的更多信息,并让它发挥作用。万分感谢!它肯定会在 Laravel 的文档中丢失,因此非常感谢
    【解决方案2】:

    如果有人碰巧发现了这个,这就是我最终不得不做的事情。我正在使用 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"/>
    

    【讨论】:

    • 这称为急切加载,仅供参考
    猜你喜欢
    • 2020-08-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 2015-04-26
    • 1970-01-01
    • 2014-10-14
    相关资源
    最近更新 更多