简体   繁体   English

Laravel Query Builder表达式返回空结果

[英]Laravel Query Builder expression to return empty result

I would like to make a function that can return a Query\\Builder that will always return an empty set. 我想创建一个函数,可以返回一个始终返回空集的Query \\ Builder。

I am making some helper functions and Query\\Builder objects get passed around. 我正在制作一些辅助函数,并且传递Query \\ Builder对象。 In certain situations, I always want the result Query\\Builder object to return an empty set, regardless of what gets added later. 在某些情况下,我总是希望结果Query \\ Builder对象返回一个空集,而不管以后添加什么。

An example is below. 一个例子如下。 I have a function that returns a query get_users_for_wednesdays , and the result gets passed to another function that adds on a where clause. 我有一个返回查询get_users_for_wednesdays的函数,结果传递给另一个添加了where子句的函数。 I don't what to have to check for the existance of a query in filter_for_steves , I just want to modify it and return a query. 我不需要检查filter_for_steves是否存在查询,我只想修改它并返回查询。

Is there an efficient query that always produces an empty set? 是否存在始终生成空集的高效查询? Ideally one that short-circuits before actually querying the database. 理想情况下,在实际查询数据库之前进行短路。

public function get_users_for_wednesdays()
{
   if (is_wednesday())
   {
       return \App\User::query();
   }
   else
   {
       // HOW TO RETURN QUERY FOR EMPTY RESULT SET HERE?
   }
}

public function filter_for_steves($users)
{
    return $users->where('name', 'steve');
}

public getThirdWednesdayStevesAttribute()
{
    $users = get_users_for_wednesday();

    return filter_for_steves($users)->get();
}

Your first two functions should be Scopes . 你的前两个函数应该是Scopes

It makes more sense to put the is_wednesday() check in the function that's building the query, but if you prefer the other way scopeUsersForWednesday() can just return the $query without modifying it when is_wednesday() returns false. 它更有意义,把is_wednesday()在大厦查询的功能检查,但如果你喜欢的其他方式scopeUsersForWednesday()可以只返回$查询,而无需修改它,当is_wednesday()返回false。

public function scopeUsersForWednesday($query)
{
    // Replace with whatever your actual query should be
    return $query;
}

public function scopeFilterForSteves($query)
{
    return $query->where('name', 'steve');
}

public function getThirdWednesdayStevesAttribute()
{
    $query = User::filterForSteves();

    if (is_wednesday()) {
        $query = $query->usersForWednesday();
    }

    return $query->get();
}

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

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