Laravel 多对多关系中的范围查询
我创建了两个模型,“Post”和“Category”。这是一种多对多的关系,非常有效 我的表格如下:Laravel 多对多关系中的范围查询,laravel,octobercms,Laravel,Octobercms,我创建了两个模型,“Post”和“Category”。这是一种多对多的关系,非常有效 我的表格如下: alex_blog_posts:在这里,帖子存储在“title”、“published”等列中 alex_blog_categories:类别存储在“title”、“parent_id”等列中 alex_blog_posts_categories:其中,使用“post_id”、“category_id”列存储帖子和类别之间的关系 假设我想筛选与名为“category 1”的类别关联的所有帖子
- alex_blog_posts:在这里,帖子存储在“title”、“published”等列中
- alex_blog_categories:类别存储在“title”、“parent_id”等列中
- alex_blog_posts_categories:其中,使用“post_id”、“category_id”列存储帖子和类别之间的关系
$posts = Post::whereHas($relationName, function ($query) {
$query->where('title', =, 'Category 1');
})->get();
$relationName-应该是在模型中定义关系的函数名(etc:“categories”)larvel具有“whereHas”:
在post模型上,您需要编写此查询:
$posts = Post::whereHas($relationName, function ($query) {
$query->where('title', =, 'Category 1');
})->get();
$relationName-应该是在模型中定义关系的函数的名称(等:“类别”)