Laravel ORM用户可以收藏多种模型 [英] Laravel ORM User can favorite Multiple Models

查看:43
本文介绍了Laravel ORM用户可以收藏多种模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出使用Laravel的Eloquent Laravel定义以下关系的最佳方法.

I am trying to find out the best way to define the following relation using Laravel's Eloquent Laravel.

我有一个用户表和3个对象(玩家,球队,联赛),用户可以将其添加为收藏夹.

I have a User table and 3 Objects ( Player, Team, League) that the user can add as favorites.

我知道我可以使用用户模型和每个对象创建三个数据透视表,但是随后我将需要运行联合查询"以列出来自用户的所有收藏夹(无论类型如何).

I know I can create three pivot tables with the User Model and each one of the objects but then I will need to run a Union query to list all favorites from user regardless of type.

User
 id

Favorite
 id
 user_id
 favorited_id  ( player_id or team_id or league id)
 favorite_type  ( player , team or league) 

Player
 id  

Team
 id

League
 id

这是我的模特.

https://www.dropbox.com/s/6au8giufaejcghc/Screen%20Shot%202014-04-07%20at%209.06.51%20AM.png

推荐答案

我将对收藏夹表执行相同的操作.laravel通过多态关系对此进行了介绍.

i'd do it the same with a Favourite table. laravel covers this with its polymorphic relations.

您的表可能看起来像

class Favourite extends Eloquent {

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

class Team extends Eloquent {

    public function favourite()
    {
        return $this->morphMany('Favourite', 'favourable');
    }
}

...

您喜欢的表格如下

Favourite
  favourable_id: int
  favourable_type: string

您可以像在 $ player-&f; favourable()这样的模型上,像普通属性一样调用它.

you'd call it like a normal property on the model like $player->favourable().

这篇关于Laravel ORM用户可以收藏多种模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆