Laravelwhere
コレクションメソッドはコレクションを変更しますか?
Laravelのドキュメントでは、これを読むことができます:
ほとんどすべてのメソッドが新しい Collection インスタンスを返すため、コレクションの元のコピーを保持できます
コレクションの変更に関する警告が表示される唯一のメソッドはtransform
、forget
しかし、私はこのコードを持っています:
$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()) {
...
そして、コレクションは最初の後に変更され、 so$descriptionsWithAnotherUnit
は常に空です。これは、その時点でコレクションにはunit_id == $request->unit
. これはフレームワークまたはドキュメントのバグですか?
そして、ここから生じる疑問: DB から再度取得せずに元のオブジェクトのコピーを保持するにはどうすればよいでしょうか? 私はこれを試しました:
$descriptions = Description::where('description', $request->description);
if ($descriptions->count()) {
$descriptionsWithSameUnit = $descriptions;
$descriptionsWithSameUnit->where('unit_id', $request->unit);
...
ただし、メソッドをオブジェクト$descriptions
に適用すると、オブジェクトも変更されますwhere
$descriptionsWithSameUnit