2016-03-18 14 views
2

これはLaravel 5.2用です。私はこれらのコードの2つの部分の違いは分かりませんが、参照によって動作するように見えるものと、そうでないものがあります。この例では参照でLaravelのクエリオブジェクトを渡す

、クエリオブジェクトは、アクションを実行する場合はfalseをチェックするために私を強制的にメソッド呼び出しからの変更のどれを保持していない:

$query = new User(); 
$query = $this->processOrderByFields($query, $request, User::getOrderByFields()); 

if ($query === false) { 
    return $this->respondError(HTTP_UNPROCESSABLE_ENTITY); 
} 

public function processOrderByFields($query, $request, $availableFields) 
{ 
    # Get fields 

    foreach ($fields as $field) { 

     # Do things to the field... 

     if (# Not important) { 
      $query = $query->orderBy(# Field, # Direction); 
     } else { 
      $badFields[] = $field; 
     } 
    } 

    if ($badFields) { 
     return false; 
    } else { 
     return $query; 
    } 
} 

しかし、これは正常に動作します:

$query = new User(); 
$this->processInclude($query, $request, Client::getIncludeRelationships()); 

public function processInclude($query, $request, $objectRelationship) 
{ 
    if ($request->get('include') && is_array($request->get('include'))) { 
     $include = array_intersect($request->get('include'), $objectRelationship); 
     foreach($include as $relation) { 
      $query->with($relation); 
     } 
    } 
} 

私はこれがwithメソッドの関係構築の一部と関係があると推測していますが、わかりません。

答えて

0

私は投稿する前に私はこれを確認したと思ったが、答えは方法は、容器と、親オブジェクトの両方と相互作用する方法であるように思える:Illuminate\Database\Eloquent\Model

Illuminate\Database\Query\Builder
public static function with($relations) 
{ 
    if (is_string($relations)) { 
     $relations = func_get_args(); 
    } 

    $instance = new static; 

    return $instance->newQuery()->with($relations); 
} 

:だから

public function orderBy($column, $direction = 'asc') 
{ 
    $property = $this->unions ? 'unionOrders' : 'orders'; 
    $direction = strtolower($direction) == 'asc' ? 'asc' : 'desc'; 

    $this->{$property}[] = compact('column', 'direction'); 

    return $this; 
} 

withは、クエリの新しい静的インスタンスを作成します(これは何を意味するのかはわかりませんが、メソッドが返された後は全体的な効果が持続すると思われます)、orderByをチェーンする必要があります。これは私の経験を確認しますが、withメソッドのニュアンスが私を逃してしまいます。

編集:

ので、第2の方法は、実際に動作しませんでした!私は、そのパラメータと他のパラメータの代わりに渡された関係インクルードクエリパラメータだけを持つエンドポイントを呼び出すことを試みるまで、それを認識しませんでした。どうやら、withクラスの静的インスタンスは、他のクエリチェーンと同じ方法で($query = $query->...)を渡す必要があります。

私はこれを数時間にわたって執着していたので、これが誰かを助けてくれることを願っています。