我建博客是为了好玩。在我的博客中,我有用户、帖子和预定义类别的固定列表。
1) 帖子属于许多类别。2) 用户可以指定类别首选项,因此属于许多类别。
我将此设置为一系列多对多关系:
在User.php
:中
/**
* A user belongs to many categories
*/
public function categoryPreferences()
{
return $this->belongsToMany('App'Category');
}
在Post.php
:中
/**
* A Post Can Have Many Likes
*
* @return 'Illuminiate'Database'Eloquent'Relations'belongsToMany
*/
public function categories()
{
return $this->belongsToMany('App'Category');
}
和Category.php
:中每个的逆
/**
* A category belongs to many users
*/
public function users()
{
return $this->belongsToMany('App'User');
}
/**
* A category belongs to many posts.
*
* @return 'Illuminiate'Database'Eloquent'Relations'belongsToMany
*/
public function posts()
{
return $this->belongsToMany('App'Post');
}
我有相应的category_post
和category_user
联接表来支持每种关系。然而,我可能想错了。
我想显示一个帖子的循环,这些帖子属于用户指定的类别,但无法理解如何做到这一点。我可以使用轻松收集用户的类别偏好
$categories = $user->categoryPreferences->pluck('id');
并且可以对帖子做同样的事情:
$categories = $post->categories->pluck('id')
然而,我不确定如何将这两个集合合并在一起。我研究过多态性,但这似乎不太正确。有人能给我指出正确的概念吗?
我认为,最好使用查询生成器,而不是ORM,代码将更好地阅读和编写。
关系$user->categoryPreferences
将为您提供一组Category模型,该模型在数据透视表中有对应用户的条目。
现在,您可以迭代该集合中的每个类别模型,并通过对集合使用each()
方法来访问帖子。
来自Laravel文档,
each方法迭代集合中的项,并将每个项传递给回调:
(在您的情况下)
$user->categoryPreferences->each(function ($category, $key) {
echo $category->post;
});
这假设您已经为类别模型定义了一个后关系。还记得过滤掉重复的帖子。