雄辩对象 - 方法链接


Eloquent Object - Method Chaining

我有以下Laravel Eloquent代码,其中会有很多方法链接:

$foo = EloquentFoo::orderBy('xyz');
if(true)
{
    $foo->whereHas('eloquentModel',function($q){
        return $q->where('name','=','john');
    });
}

鉴于条件复杂,我需要实例化 Eloquent Query Builder,而无需使用"orderBy"或任何其他静态方法。

我尝试使用以下方法,但惨遭失败(不知道为什么):

$foo = new EloquentFoo;
// get the query
$fooQuery = EloquentFoo::query();
// chain methods    
if (whatever) $fooQuery->whateverMethod();
// execute
$fooQuery->get();

一个简单的解决方法:我将我的主键与不存在的东西(不是最佳解决方案)进行比较,有兴趣查看其他解决方案,尽管我认为这可能会有所帮助:

$foo = EloquentFoo::where('id','!=','0'); // id is the primary key and there is no row with value 0
// so basically above I am searching everything
// Perform Chaining Operation 
if(true)
{
    $foo->whereHas('eloquentModel',function($q){
        return $q->where('name','=','john');
    });
}

注意:您可以在链中多次使用 id,它仍然有效:

EloquentFoo::where('id','!=','0')->where('id','!=','0')->get() 

希望它有所帮助(我知道它根本不是最佳的)。