2015-02-09 104 views
1

我正在使用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中的工会,但视频和帖子表列“并不相同。 有什么建议吗?

回答

0

这里是一个雄辩的风格来实现这一目标。假设我找到标签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()); 
1

使用雄辩的力量。

创建模型文件(Post.php,Video.php, Tag.php)。

post.php中

class Post extends Eloquent { 

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

Video.php

class Video extends Eloquent { 

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

Tag.php

class Post 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(); 
+0

感谢您的回答,但在我的问题中,我说我建立了多对多的多态关系,我不想改变这种结构。我自己回答了这个问题。 – thangngoc89 2015-02-12 16:01:50

相关问题