代码之家  ›  专栏  ›  技术社区  ›  Javed

laravel:在关系中搜索查询

  •  2
  • Javed  · 技术社区  · 7 年前

    当我在我的应用程序中添加新帖子时 7 tables 影响我添加单个帖子的时间。要获取包含所有post数据的所有post,我的简单查询如下所示:

    $userPost   = Post::with(['product','postattribute.attribute.category','user.userDetails'])
                            ->offset($offset)
                            ->limit($limit)
                            ->whereStatus("Active")
                            ->whereIn('product_id', $userApprovalProductIDs)
                            ->orderBy('id','desc')
                            ->get();
    

    所以它会重新运行我想要的所有数据。现在我想在所有表中实现搜索查询,目前我只能搜索 posts 表。

    如果我在搜索 category categoryTitle 我试着像

    where('category.title','=', $serachTitle)
    

    但在我的情况下是行不通的。

    POST 模型关系:

    public function user() {
        return $this->belongsTo(User::class);
    }
    
    public function product() {
        return $this->belongsTo(Product::class);
    }
    
    public function postattribute() {
        return $this->hasMany(PostAttribute::class);
    }
    

    POSTATTRIBUTES 模型关系:

      public function post() {
        return $this->belongsTo(Post::class);
    }
    
     public function attribute() {
        return $this->belongsTo(Attribute::class);
    }
    

    ATTRIBUTES 模型关系:

       public function category() {
        return $this->belongsTo(Category::class);
    }
    
     public function attributes() {
        return $this->belongsTo(Attribute::class);
    }
    

    我该怎么做?

    1 回复  |  直到 7 年前
        1
  •  1
  •   M Khalid Junaid    7 年前

    要对嵌套关系应用筛选器,可以使用 whereHas

    $userPost   = Post::with(['product','postattribute.attribute.category','user.userDetails'])
        ->offset($offset)
        ->limit($limit)
        ->whereStatus("Active")
        ->whereIn('product_id', $userApprovalProductIDs)
        ->whereHas('postattribute.attribute.category', function ($query) use($serachTitle) {
            $query->where('title', '=', $searchTitle);
        })
        ->orderBy('id','desc')
        ->get();
    

    Querying Relationship Existence

    从评论中我了解到你想知道如何在每个关系中搜索一篇文章,我已经添加了一个例子来搜索类别标题

    ->whereHas('postattribute.attribute', function ($query) use($var) {
        $query->where('some_field_of_attribute_table', '=', $var);
    })
    
    ->whereHas('postattribute', function ($query) use($var) {
        $query->where('some_field_of_postattribute_table', '=', $var);
    })