2015-02-09 106 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

相關問題