2016-04-18 1 views
0

Laravel コレクションのメソッドはコレクションを変更しますか?Laravel 'コレクションメソッドがコレクションを変更する場所

ほぼすべてのメソッドは、コレクション

そして持っている唯一の方法の元のコピーを保存することができ、新しいコレクションのインスタンスを返します。Laravel documentationあなたがこれを読むことができるオン

コレクションの変更に関する警告はtransformforget

ですが、私はこのコードを持っています:

$descriptions = Description::where('description', $request->description); 

    if ($descriptions->count()) { 
     $descriptionsWithSameUnit = $descriptions->where('unit_id', $request->unit); 
     if ($descriptionsWithSameUnit->count()==0) { 
      $descriptionsWithAnotherUnit = $descriptions->where('unit_id', '!=', $request->unit); 
      if ($descriptionsWithAnotherUnit->count()) { 
     ... 

$descriptionsWithAnotherUnitの後にコレクションが変更されるのは、その時点でコレクションには、unit_id == $request->unitのレコードしかないためです。これはフレームワークやドキュメントのバグですか?

ここからの質問元のオブジェクトのコピーをデータベースから再度取得せずに保持するにはどうすればよいですか?私はこれを試してみました:

$descriptions = Description::where('description', $request->description); 

if ($descriptions->count()) { 
    $descriptionsWithSameUnit = $descriptions; 
    $descriptionsWithSameUnit->where('unit_id', $request->unit); 
    ... 

しかし、私は$descriptionsWithSameUnitオブジェクト

答えて

1

where方法を適用すると$descriptionsオブジェクトも修正されて最初にすることは、それはあなたがgetを使用する必要があるコレクションを取得することですので、あなたの場合コレクションを取得したい、あなたが実行する必要があります。

$descriptions = Description::where('description', $request->description)->get(); 

とだけでなく、:

$descriptions = Description::where('description', $request->description); 

2つ目は、コレクションにwhere methodを使用して演算子を使用するには何の可能性はそう、ありませんということです。

$descriptionsWithAnotherUnit = $descriptions->where('unit_id', '!=', $request->unit); 

は完全に間違っています。ここではfilterメソッドを使用する必要があります。

+0

私は理解しています、私はEloquent whereメソッドを使用しています。コレクションはありません。 Thks、私はそれを見ていませんでした。 –

+0

@MariaVilaró問題ありません。あなたが見ているそれらの方法は、Eloquentと同じではありません –

関連する問題