Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用多个过滤器和分页简化雄辩的Laravel?_Php_Mysql_Laravel_Object_Eloquent - Fatal编程技术网

Php 使用多个过滤器和分页简化雄辩的Laravel?

Php 使用多个过滤器和分页简化雄辩的Laravel?,php,mysql,laravel,object,eloquent,Php,Mysql,Laravel,Object,Eloquent,我的问题是如何简化使用Laravel分页的多个有说服力的查询 我正在建立一个Laravel网站,在这个网站上人们可以分享某些食谱 我有多个变量,成员可以搜索、筛选和查看。 因此,会员可以发布食谱并添加: -类型 -持续时间 -国家 -平台 其思想是有一个包含所有配方的页面,但也有一些页面只应用了1、2或更多过滤器的配方。例如,冷5分钟食谱或德国暖长食谱 我使用Laravel5.7,现在我用不同的where语句构建各种查询。像这样: public static function getRecip

我的问题是如何简化使用Laravel分页的多个有说服力的查询

我正在建立一个Laravel网站,在这个网站上人们可以分享某些食谱

我有多个变量,成员可以搜索、筛选和查看。 因此,会员可以发布食谱并添加: -类型 -持续时间 -国家 -平台

其思想是有一个包含所有配方的页面,但也有一些页面只应用了1、2或更多过滤器的配方。例如,冷5分钟食谱或德国暖长食谱

我使用Laravel5.7,现在我用不同的where语句构建各种查询。像这样:

 public static function getRecipesMixFilter($cid, $pid, $tid, $did)
{
    $recipes = self::with(['member', 'platform', 'member.platform', 'member.duration', 'member.type'])->whereActive(1)->whereHas('member', function ($query) use ($cid, $pid, $tid, $did) {
            $query->where('country_id', '=', $cid)
            ->where('platform_id', '=', $pid)
            ->where('type_id', '=', $tid)
            ->where('duration_id', '=', $did);
    })->orderBy('updated_at', 'desc')->paginate(24);

    return $recipes;
}
但最简单的方法是什么呢?现在我有15个不同的查询,我觉得可能是1。因此,->其中('platform_id','=',1)等是可选的

当我尝试对每个对象进行筛选时,例如第一个平台,然后键入,等等,我无法应用分页


有没有办法简化这一点?我可以将Ajax过滤器与Laravel分页一起使用吗?

您可以通过这样做使它们成为可选的:

public static function getRecipesMixFilter($cid = null, $pid = null, $tid = null, $did = null)
{
    $recipes = self::with(['member', 'platform', 'member.platform', 'member.duration', 'member.type'])
        ->whereActive(1)
        ->whereHas('member', function ($query) use ($cid, $pid, $tid, $did) {
            if ($cid) {
                $query->where('country_id', '=', $cid)
            }
            if ($pid) {
                $query->where('platform_id', '=', $pid)
            }
            if ($tid) {
                $query->where('type_id', '=', $tid)
            }
            if ($did) {
                $query->where('duration_id', '=', $did)
            }
        })->orderBy('updated_at', 'desc')->paginate(24);

    return $recipes;
}

您返回的是
$username
,但该变量在方法中的任何地方都没有定义。我只是编辑了它,这样它就可以工作&没有$username。您可以尝试将所有参数都设置为可选参数,然后仅将每个参数添加到已设置的筛选器中,如
if($cid)$query->where('country_id','=',$cid),等等。但我发现这是一个联合查询,但这似乎不起作用trick@DontPanic我认为您应该发布关于如何使用可选参数的答案。那将解决他的问题