2016-09-25 134 views
1

我有一张海报,可以有一个用户。海报可以有许多标签,标签可以有许多海报。现在我想要检索由特定用户创建的海报中使用的所有不同标签。我使用laravel,所以,ORM是雄辩的。如果有人能够使用雄辩提供给我一个解决方案,那将是非常感谢。我只想检索标签。
User类:通过一对多关系检索多对多关系

class User extends Model { 
    public function posters() { 
     return $this->hasMany(Poster::class); 
    } 
} 

Poster类:

class Poster extends Model { 
    public function user() { 
     return $this->belongsTo(User::class); 
    } 
    public function tags() { 
     return $this->belongsToMany(Tag::class); 
    } 
} 

Tag类:

class User extends Model { 
    public function posters() { 
     return $this->belongsToMany(Poster::class); 
    } 
} 

回答

1

whereHas方法允许通过相关模型的属性搜索记录。它也适用于嵌套关系,因此您可以使用它来搜索给定用户使用的所有标签。

下应该做的伎俩:

$tags = Tag::whereHas('posters.user', function($query) { 
    $query->whereId($userId); 
})->get(); 
+0

Thansk @ jedrzej.kurylo!像魅力一样工作!你能否告诉我如何为每个标签返回海报数量?谢谢。 –