【问题标题】:Laravel Eloquent condition with "with" relationship datas which impact the outputLaravel Eloquent 条件与影响输出的“with”关系数据
【发布时间】:2020-04-21 00:03:56
【问题描述】:

这是我的代码:

$search = request()->get('search');

    if(Auth::user()->hasRole('admin') || true) {
        list($orderBy, $orderDirection) = explode('.', request()->get('sort_by'));
        $prestations = Prestation::with(
            [
            'service' => function($service) use($search){
                $service->select(['id','name']);
                ->where('name', 'regexp', "/$search/i"); <--- HERE THE PROBLEM, i get some "null" values in the output, it's not a really condition to display or not
            },
            'facility' => function($facility) {
                $facility->select(['id','name']);
            }
            ]
        )
            ->where('name', 'regexp', "/$search/i") <-- I want to do this with service name
            ->orderBy($orderBy, $orderDirection)
            ->simplePaginate(50);

        $res = [
            'results' => $prestations,
            'total' => Prestation::all()->count(),
        ];

        return $res;

我想对我的“服务:名称”做一个 where 条件,这会真正影响输出,并且不显示值为“null”的数据,例如 -&gt;where('name', 'regexp', "/$search/i"),但我不知道如何访问“with”关系的“service:name”。

谢谢你,新年快乐!

【问题讨论】:

标签: php laravel eloquent laravel-query-builder


【解决方案1】:

您可以为此使用 whereHas

$prestations = Prestation::whereHas('service', function($subQuery) use($search) {
                $subQuery->where('name', 'like', '%' . $search . '%');
            })->with(
    [
        'service' => function($service) use($search){
            $service->select(['id','name'])->where('name', 'like', '%' . $search . '%');
        },
    ]
)->orderBy($orderBy, $orderDirection)->simplePaginate(50);

【讨论】:

    【解决方案2】:

    您可以使用 LIKE 运算符来做到这一点:

    $prestations = Prestation::with(
            [
                'service' => function($service) use($searchTerm){
                    $service->select(['id','name'])->where('name', 'LIKE', "%$searchTerm%");
                },
            ]
        )->orderBy($orderBy, $orderDirection)->simplePaginate(50);
    
    1. 如果要搜索包含搜索词的记录,请使用LIKE '%$searchTerm%'
    2. 如果要搜索以搜索词开头的记录,请使用LIKE '$searchTerm%'
    3. 如果您想搜索以搜索词结尾的记录,请使用LIKE '%$searchTerm'

    希望对你有所帮助

    【讨论】:

    • 嗨,谢谢你的建议,我的问题是我想在“with()”之后的地方做这个
    • with 后的 where 条件将应用于父模型,即 Prestation。因此,要么直接在服务关系中定义它,要么使用上述关系条件,因为这是 laravel 中的最佳实践。
    猜你喜欢
    • 2020-04-21
    • 1970-01-01
    • 2017-03-21
    • 2020-10-26
    • 2019-06-22
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 2016-11-21
    相关资源
    最近更新 更多