简体   繁体   English

在 Laravel 中搜索相关模型

[英]Search in the related model in Laravel

I have post table like this :我有这样的帖子表:

id | post_title | category_id

and this is category table这是类别表

id | category_title

this is the relation between these two which is inside post model :这是这两者之间的关系,在 post 模型中:

  public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }

I want to get the record of post table where category_title or post_title matches the keyword entered by user.我想获取 category_title 或 post_title 与用户输入的关键字匹配的帖子表的记录。

I'm retrieving data something like:我正在检索如下数据:

Post::where(['title'=>$request->title])->with('category')->paginate(10);

but here it is only fetching Post title but i also want it to search it in category title.但在这里它只获取帖子标题,但我也希望它在类别标题中搜索它。

Any help is highly appreciated.任何帮助都受到高度赞赏。

Post::where('title', 'like', '%'.$request->title.'%')->with(['category' => function($query) use ($request){
        $query->where('category_title', 'like', '%'.$request->title.'%');
    }])->paginate(10);

In the above code snippet在上面的代码片段中

  1. We are fetching the title which matches with the request我们正在获取与请求匹配的标题
  2. with(['category' => function($query) use ($request) : laravel matches the result into relationship using closure function which accepts one parameter $request and again we are filtering the relationship with this parameter $request->title which is coming through Request $request with(['category' => function($query) use ($request) : laravel 使用接受一个参数$request闭包函数将结果匹配到关系中,我们再次过滤与这个参数 $request->title 的关系正在通过Request $request

You can use the code above or you can make a scope for reusability.您可以使用上面的代码,也可以为可重用性创建一个范围。

Post::->where('title', 'like', '%'.$request->title.'%')->with(['category' => function($query) use ($request){
    $query->where('category_title', 'like', '%'.$request->title.'%');
}])->paginate(10);

Try this:-尝试这个:-

$keyword = $request->input('title');

Post::with('category')
     ->where('title', 'like','%'.$keyword.'%')
     ->orWhere('category.category_title','like','%'.$keyword.'%')
     ->paginate(10);

you should use orWhereHas :你应该使用orWhereHas

 Post::where(['title' => $request->title])->
        orWhereHas('category',function ($query)use($request){
            $query->where('category_title',$request->title);
        })->with('category')-> paginate(10);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM