programing

과부하 특성 라라벨 MongoDB의 간접 수정

instargram 2023. 6. 21. 22:09
반응형

과부하 특성 라라벨 MongoDB의 간접 수정

저는 Laravel과 함께 MongoDB를 사용하고 있습니다.라는 컬렉션이 있습니다.categories하나의 문서를 가지고 있는 것.

[
  {
    "_id": "567dc4b4279871d0068b4568",
    "name": "Fashion",
    "images": "http://example.com/1.jpg",
    "specifics": [
      "made"
    ],
    "brands": [
      {
        "name": "Giordano",
        "logo": "http://example.com/"
      },
      {
        "name": "Armani",
        "logo": "http://example.com/"
      }
    ],
    "updated_at": "2015-12-25 22:40:44",
    "created_at": "2015-12-25 22:35:32"
  }
]

위 문서의 specific array에 specific을 추가하는 기능을 만들려고 합니다.

내 요청 본문은 다음과 같습니다.

HTTP: POST
{
    "specifics": [
        "material"
    ]
}

그리고 저는 이 요청을 다음과 같은 기능으로 처리하고 있습니다.

/**
 * Add specs to category
 * @param string $category_id
 * @return Illuminate\Http\JsonResponse
 */
public function addSpecifics($category_id)
{
    $category = $this->category->findOrFail($category_id);
    $category->specifics[] = $this->request->get('specifics');
    $status_code = config('http.UPDATED');
    return response()->json($category->save(), $status_code);
}

하지만 이 전화를 걸면 다음과 같은 오류가 발생합니다.

CategoryController.php line 101의 ErrorException: 오버로드된 속성 App\Category::$specific은 영향을 주지 않습니다.

이것을 고치는 것을 도와주세요.

저는 이 패키지를 MongoDB용으로 https://github.com/jenssegers/laravel-mongodb 를 사용하고 있습니다.

모델 속성에 액세스하는 방법은 Mandwell에서 구현되므로 $category->specific에 액세스할 때 해당 속성 값의 복사본을 반환하는 magic__get() 메서드가 호출됩니다.따라서 해당 복사본에 요소를 추가하면 원본 속성의 값이 아닌 복사본만 변경됩니다.그렇기 때문에 무엇을 하든 아무런 효과가 없을 것이라는 오류가 발생하는 것입니다.

$category->specifics 배열에 새 요소를 추가하려면 다음과 같은 세터 방식으로 속성에 액세스하여 마법__set()가 사용되는지 확인해야 합니다.

$category->specifics = array_merge($category->specifics, $this->request->get('specifics'));

단일 항목을 배열에 추가하려는 경우 다음 방법을 사용할 수 있습니다.

PHP:

$new_id = "1234567";
$object->array_ids = array_merge($object->array_ids, [$new_id]);

이 일은 나를 위한 것입니다!

변수를 온도 변수에 저장합니다.

// Fatal error    
$foo = array_shift($this->someProperty);

// Works fine
$tmpArray = $this->someProperty;
$foo = array_shift($tmpArray);

Model을 확장하는 클래스 내부의 어레이에서도 동일한 문제가 발생했습니다.

이 코드$this->my_array[$pname]=$v;내가 선언할 때까지 작동하지 않았습니다.protected $my_array = [];

또 다른 간단한 대안:

function array_push_overloaded($source, $element) {
  $source[] = $element;
  return $source;
}

예:

$category->specifics = array_push_overloaded($category->specifics, $this->request->get('specifics'));

Enholder 컬렉션을 직접 수정하려고 하지 말고 컬렉션을 Array에 캐스팅하고 수정을 위해 해당 어레이를 사용합니다.

$model = Model::findOrFail($id);

$array = $model->toArray();
$array['key'] = $value;

언급URL : https://stackoverflow.com/questions/34467076/indirect-modification-of-overloaded-property-laravel-mongodb

반응형