Laravel雄辩搜索两个可选字段 [英] Laravel Eloquent search two optional fields

查看:73
本文介绍了Laravel雄辩搜索两个可选字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $ users = User :: where('ProfileType' ,'=',2)
- > where(function($ query){
$ query-> where('BandName','LIKE',%$ artist%);
$ query-> or_where('类型','LIKE','%$ genre%');
}) - > get();

当用户执行空搜索时,返回所有结果都可以正常工作,但我不知道如何调整这个,以便在现在的时候搜索带名,反之亦然。

解决方案

建立在Vinicius的答案下,

  //实例化一个Query对象
$ query = User :: where('ProfileType','=' '2');

//向查询添加一个子句
if($ artist = Input :: get('artist')){
$ query-> where('BandName' ,LIKE,%$ artist%);
// Temp Usernamesearch
$ query-> or_where('NickName','LIKE',%$ artist%);
}

//如果艺术家不是空,类型 - 切换功能
if($ genre = Input :: get('genre')){
$ func =($艺术家)? 'or_where':'where';
$ query-> $ func('类型','LIKE',%$类型%);
}

//执行查询并获取结果
$ users = $ query-> get();

如果$ artist没有设置,则第二个可选字段必须使用or_where。


感谢您的帮助


I'm trying to search two optional tables using eloquent:

$users  = User::where('ProfileType', '=', 2)
                ->where(function($query) {
                    $query->where('BandName', 'LIKE', "%$artist%");
                    $query->or_where('Genre', 'LIKE', "%$genre%");
                })->get();

This works fine for return all results when a user does an empty search, but I am not sure how to adjust this for to search for bandname when that is present and vise versa.

解决方案

Building on Vinicius' answer here's what worked:

// Instantiates a Query object
$query = User::where('ProfileType', '=', '2');

// Adds a clause to the query
if ($artist = Input::get('artist')) {
    $query->where('BandName', 'LIKE', "%$artist%");
    // Temp Usernamesearch
    $query->or_where('NickName', 'LIKE', "%$artist%");
}

// Genre - switch function if artist is not empty
if ($genre = Input::get('genre')) {
    $func = ($artist) ? 'or_where' : 'where';
    $query->$func('Genre', 'LIKE', "%$genre%");
}

// Executes the query and fetches it's results
$users = $query->get();

Turns out that the second optional field must use or_where only if $artist is not set.

Thanks for your help

这篇关于Laravel雄辩搜索两个可选字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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