【问题标题】:Laravel Search in multiple tablesLaravel 在多个表中搜索
【发布时间】:2018-04-14 22:07:40
【问题描述】:

我在一个模型中制作了一个 searchScope。这是完美的工作。但我需要为多个模型创建这个搜索字段。当我搜索一个字符串时,它必须扫描其他表。到目前为止我做了什么:

public function scopeSearch(Builder $query, $search)
{
    $query->whereHas('translations', function ($q) use ($search) {
        $q->where('value', 'like', '%' . $search . '%');
    })
        ->orWhere('title', 'LIKE', '%' . $search . '%')
        ->orWhere('sub_body', 'like', '%' . $search . '%')
        ->orWhere('body', 'like', '%' . $search . '%');
}

翻译表包含所有其他模型的翻译值。那挺好的。因为我只想在这个查询中添加 2-3 个额外的模型。我怎样才能做到这一点?提前致谢。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    一种方法是您可以从父表开始搜索,然后继续。比如如果你想同时搜索帖子、cmets 和他们的回复,那么你可以从父表开始,即帖子。

    public function scopeSearchGlobal($query, $search){
       $query->where('body', 'LIKE', '%' . $search . '%');
       $query->with(['comments', function($comment) use ($search){
           $comment->where('comment', 'LIKE', '%' . $search . '%');
           $comment->with(['replies' => function($reply) use ($search){
               $reply->where('reply', 'LIKE', '%' . $search . '%');
           }]);
       }]);
    }
    

    请记住,此搜索是针对相互关联的表。这是搜索多个表的一般想法。 但是,如果您有翻译表并且它具有所有其他模型的翻译值,那么您可以只搜索翻译表并调用其中的每个关系。

    public function scopeSearch($query, $search)
    {
       $query->whereHas('translations', function ($q) use ($search) {
        $q->where('value', 'like', '%' . $search . '%');
       })->with('posts', 'blogs', 'comments', 'replies'); 
       // define relations that are associated with translations model and call 
          them here. So it will search just the translations table and brings all 
          associated results
    }
    

    希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 2020-03-20
      • 2018-09-25
      • 2017-06-03
      • 2020-12-21
      • 2021-02-13
      • 1970-01-01
      相关资源
      最近更新 更多