【发布时间】:2019-08-20 17:42:27
【问题描述】:
假设我有多个用户可以看到的帖子和视频。
- users
- id
- posts
- id
- videos
- id
- user_accessables (pivot)
- id
- user_id
- accessable_id
- accessable_type
在这样的例子中,我已经这样设置了我的用户关系,但感觉有些不对
class User extends Model {
public function posts() {
return $this->morphedByMany(
Post::class,
'accessable',
'user_accessables'
);
}
public function videos() {
return $this->morphedByMany(
Video::class,
'accessable',
'user_accessables'
);
}
public function allowedEntities() {
return ($this->posts)->merge($this->videos);
}
}
使用allowedEntities(),我可以得到两个模型的集合。
但是,我认为使用多态关系是通过关系返回实体的集合,而不是需要组合关系,对吧?
我在使用数据透视表理解多态时遇到问题(文档中的标记示例似乎不是相同的场景)。
因为现在我做不到:
$collection = collect(); // multiple models of Video & Post
$user->allowedEntities()->sync($collection);
【问题讨论】:
-
你的关系是正确的。无法定义返回所有相关模型组合的关系。
标签: php laravel eloquent relationship