【问题标题】:Laravel polymorphic relationship with pivotLaravel 与枢轴的多态关系
【发布时间】: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


【解决方案1】:

正如@Jonas Staudenmeir 所说,不可能有一个返回所有相关模型的关系,但是您可以在模型上定义一个方法,该方法返回一个包含您需要的所有实体的查询构建器对象(在文档上搜索)。

【讨论】:

    猜你喜欢
    • 2020-04-13
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 2018-05-16
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多