【问题标题】:Search all rows with the same tag in many to many polymorphic在多对多多态中搜索具有相同标签的所有行
【发布时间】:2015-02-09 06:07:44
【问题描述】:

我正在使用 Laravel 5,并且与我的标记系统有这样的多对多多态关系。

posts
    id - integer
    name - string

videos
    id - integer
    name - string
    url - string


tags
    id - integer
    name - string

taggables
    tag_id - integer
    taggable_id - integer
    taggable_type - string

现在,我正在创建一个搜索页面来搜索具有相同标签的所有帖子和视频?我考虑过 MySQL 中的联合,但视频和帖子表列不相等。 有什么建议吗?

【问题讨论】:

    标签: php mysql eloquent laravel-5


    【解决方案1】:

    使用雄辩的力量。

    创建模型文件(Post.phpVideo.phpTag.php)。

    Post.php

    class Post extends Eloquent {
    
        public function tags()
        {
            return $this->belongsToMany('Tag');
        }
    }
    

    视频.php

    class Video extends Eloquent {
    
        public function tags()
        {
            return $this->belongsToMany('Tag');
        }
    }
    

    标签.php

    class Tag extends Eloquent {
    
        public function posts()
        {
            return $this->belongsToMany('Post');
        }
    
        public function videos()
        {
            return $this->belongsToMany('Video');
        }
    
    }
    

    您可以在 Laravel Eloquent Relationships 文档中阅读更多信息。

    接下来,创建两个数据透视表,而不是 taggeables:第一个 post_tag 使用字段 tag_idpost_id 将帖子与标签连接起来,第二个 tag_video 使用字段 video_idtag_id 进行连接带有标签的视频。

    最后,要获取具有相同标签 ID(假设为 $tag_id)的所有帖子和视频,您可以执行以下操作(如果您的 Post.php 模型确实包含 tags() 方法):

    对于帖子:

    $posts = Post::whereHas(`tags`, function($q) {
        $q->where('id', '=', $this->id);
    })->orderBy('name', 'ASC')->get();
    

    对于视频:

    $videos = Video::whereHas(`tags`, function($q) {
        $q->where('id', '=', $this->id);
    })->orderBy('name', 'ASC')->get();
    

    【讨论】:

    • 谢谢你的回答,但在我的问题中,我说我建立了多对多的多态关系,我不想改变那个结构。我自己回答了这个问题。
    【解决方案2】:

    这是实现此目的的 Eloquent 风格。假设我找到标签 id = 1 的所有帖子和视频;

    $tag = Tag::with(['posts', 'videos'])->find(1);
        $relations = $tag->getRelations();
    
    
    $posts = $relations['posts']; // Collection of Post models
    $videos = $relations['videos']; // Collection of Video models
    
    $allRelations = array_merge($posts->toArray(), $videos->toArray());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      • 2017-12-04
      • 2022-06-25
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      • 2011-09-25
      相关资源
      最近更新 更多