【问题标题】:Laravel : Search Query Within RelationshipLaravel:关系内的搜索查询
【发布时间】:2018-11-13 09:22:57
【问题描述】:

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

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

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

如果我正在使用 categoryTitle 搜索 category 表,我正在尝试编写类似代码

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);
}

我该怎么做?

【问题讨论】:

  • 你能包括你的模型定义吗?
  • @MKhalidJunaid 好的,等等,,

标签: laravel laravel-5.5 laravel-query-builder


【解决方案1】:

要对嵌套关系应用过滤器,您可以使用 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

从 cmets 我的理解是你想知道如何在每个关系中搜索帖子,我已经添加了一个示例来搜索类别标题

->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);
})

【讨论】:

  • 如果postattribute.attribute.category 所有表的title 都有相同的字段,我该怎么办?我如何验证特定表@MKhalidJunaid
  • 所有表格都有相同的标题字段我没有得到这个可以解释更多或者如果你能更新你的问题会更好
  • 这 3 个表 postattribute.attribute.category 都有一个相同的字段,即 post_id。如果我想用post_idpostattribute 表中搜索,我与attribute.category 表有何不同。
  • @Javed 我已经更新了我的答案,如果它解决了你的问题,请告诉我
猜你喜欢
  • 1970-01-01
  • 2020-11-21
  • 1970-01-01
  • 2015-10-30
  • 2015-06-11
  • 1970-01-01
  • 2014-11-23
  • 1970-01-01
  • 2019-01-10
相关资源
最近更新 更多