雄辩的关系查询范围 [英] Eloquent query scope on relationship

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

问题描述

我有两个分别称为PageUser的模型,并且我已经建立了Eloquent关系,如下所示:

I have two models called Page and User and I've set up the Eloquent relation as follows:

public function user() {
  return $this->belongsTo('User')
}

当我dd(Page::with('user')->get())时,我得到正确的结果.但是现在我想对此结果进行搜索过滤.

When I dd(Page::with('user')->get()) I get the right result. But now I want to have a search filter on this result.

我使用了scopeSearch,但不确定如何在结果集上进行搜索.

I've used a scopeSearch but I'm not sure how to search on the resultset.

目前,我有一个这样的范围:

At the moment I have a scope like this:

public function scopeSearch($query, $search) {
  $query->where('username', 'LIKE', '%'.$search.'%')
     ->orWhere('name', 'LIKE', '%'.$search.'%')
}

所以当我Page::with('user')->search('Test')->get()时,它不起作用. 问题(可能是)username列是User表的一部分,而name列是Page表的一部分.

So when I Page::with('user')->search('Test')->get() it is not working. The problem (probably) is that the username column is part of the User table and the name is part of the Page table.

我如何能够使用范围或熟悉的对象来搜索结果集,而无需在大多数查询中重复进行搜索?

How would I be able to use a scope or something familiar, to search on the resultset, without repeating it in most of the queries?

推荐答案

您需要在User模型中创建scopeSearch,并且您应该使用这种方式:

You need to create scopeSearch in User model and you should use it this way:

$posts = Page::with('user')->whereHas('user', function($q) use ($search)
{
    $q->search($search);

})->get();

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

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