范围查询在多对多关系中 [英] Scope query in a many to many relationship

查看:45
本文介绍了范围查询在多对多关系中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个模型,发布"和类别".这是一种多对多关系,效果很好.

I created 2 models, "Post" and "Category". This is a many to many relationship, works great.

我的表格如下:

  • alex_blog_posts:其中的帖子存储在列中,例如"title","published"等...
  • alex_blog_categories:其中类别存储在列中,例如"title","parent_id"等...
  • alex_blog_posts_categories:关系与帖子和类别之间的关系存储在列"post_id","category_id"中

假设我要过滤与名称为类别1"的类别相关的所有帖子

Let's assume I want to filter all posts that are associated to a category with name : "Category 1"

public function scopeFilterCategory($query) {
    $query->join(????); // My problem is to replace the ???
    $query->where('title', '=', 'Category 1');
    return $query;
}

我对10月和laravel还不熟悉,我被困在这里.对于laravel专家来说,这可能非常简单,但是我需要一个具体的示例,说明某些事情无法正常工作:/

I'm not familiar enought with october and laravel yet and I'm stuck here. Probably very simple for laravel expert but I need a concrete example of something working cause all things I tried failed :/

感谢您的帮助

推荐答案

laravel具有"whereHas":

laravel have the "whereHas":

https://laravel.com/docs/5.5/eloquent -relationships#querying-relationship-existence

在帖子模型上,您需要编写以下查询:

On the post model you need the write this query:

$posts = Post::whereHas($relationName, function ($query) {
     $query->where('title', =, 'Category 1');
})->get();

$ relationName-应该是在模型中定义关系的函数的名称(例如:"categories")

$relationName - should be the name of the function that define the relation in your model (etc: 'categories')

这篇关于范围查询在多对多关系中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆