【发布时间】:2014-11-15 09:15:15
【问题描述】:
让我有 3 个名为 user、admin、post 的表
我的post表结构是
-id
-poster_id
-poster_type //if value is 1 then poster_id will be releted with user table. if value is 2 then poster_id releted with admin table.
现在如何根据poster_type值写belongsTo与两个表的关系
我想在 Post 模型中这样做
public function Author(){
return $this->belongsTo('User', 'poster_id')->where('poster_type', '1') //poster_type is the field of post table.
}
【问题讨论】:
-
您可能应该重新考虑您的数据库设计,并为用户和管理员使用 users 表,并使用一个布尔列来确定用户是否是管理员。
-
管理员也是用户。因此,为所有其他用户的管理员和用户创建单独的表是没有意义的。您可以为每个用户组创建每个表,或者在用户表中将名为“组”或“类型”的列放置到不同的用户组。
-
其实这不是我的数据库。我只想了解如何根据值关联表格。例如:如果值为 1,那么我想与表
x关联,如果值为 2,那么我想与表y关联。 -
您可以使用 laravel.com/docs/eloquent#polymorphic-relations 来实现这一点,只需将
poster_type更改为User/Admin并确保您拥有这 2 个 Eloquent 模型。 -
stackoverflow.com/questions/43668153/… 请查看此链接以获取解决方案
标签: laravel laravel-4 eloquent