Laravel Eloquent with () 메서드는 'where'에서는 작동하지만 'Model :: find ()'에서는 작동하지 않습니다.

soheil yo

Laravel Eloquent with() 방법을 사용하여 3 개의 테이블 사이에 관계를 갖고 싶습니다 . 이것은 내 코드입니다 ( 관계는 모델에 설정 됨 ).

    $request_form = RequestForm::find(7)->with(['RequestFormsCheck' => function ($q) {
        $q->orderBy("created_at", "DESC")->with('RequestFormsCheckOptions');
    }])->get();

    dd($request_form);

하지만이 코드는 이 출력 request forms반환하는 것을 제외하고 모두 반환합니다 id = 7.

Collection {#895 ▼
  #items: array:4 [▼
    0 => RequestForm {#796 ▶}
    1 => RequestForm {#797 ▶}
    2 => RequestForm {#798 ▶}
    3 => RequestForm {#799 ▶}
  ]
}

내가 교체 할 때 ->get()->first()그것을 바로 반환 request form,하지만이 id1 :(

하지만이 코드는 훌륭하게 작동합니다.

        $request_form = RequestForm::where('id', 7)->with(['RequestFormsCheck' => function ($q) {
            $q->orderBy("created_at", "DESC")->with('RequestFormsCheckOptions');
        }])->first();

        dd($request_form->toArray());

그리고 이것은 출력입니다 ( 이것은 내가 얻을 것으로 기대하는 것입니다 ).

array:12 [▼
  "id" => 7
  "name" => "Jack"
  "email" => "[email protected]"
  "telephone" => null
  "description" => "..."
  "site" => "http://branch.local/"
  "item_id" => 10
  "lang" => "en"
  "read" => 1
  "created_at" => "2018-05-15 11:09:47"
  "updated_at" => "2018-05-20 05:24:41"
  "request_forms_check" => array:1 [▼
    0 => array:8 [▼
      "id" => 1
      "request_form_id" => 7
      "type" => 2
      "request_forms_check_options_id" => null
      "description" => "custom note"
      "created_at" => "2018-05-15 11:48:36"
      "updated_at" => "2018-05-15 11:48:36"
      "request_forms_check_options" => null
    ]
  ]
]

다음은 내 마이그레이션입니다.

    Schema::create('request_forms', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name', 100)->nullable();
        $table->string('email', 100)->nullable();
        $table->string('telephone', 20)->nullable();
        $table->text('description')->nullable();
        $table->string('site', 100);
        $table->integer('item_id');
        $table->string('lang');
        $table->timestamps();
    });

    Schema::create('request_forms_check_options', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title', 500);
        $table->timestamps();
    });

    Schema::create('request_forms_checks', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('request_form_id')->unsigned();
        $table->foreign('request_form_id')->references('id')->on('request_forms')->onDelete('cascade');
        $table->tinyInteger('type')->comment("1: option, 2:description");
        $table->integer('request_forms_check_options_id')->unsigned()->nullable();
        $table->foreign('request_forms_check_options_id')->references('id')->on('request_forms_check_options')->onDelete('cascade');
        $table->text('description')->nullable();
        $table->timestamps();
    });
올루와 토비 사무엘 오 미사 킨

먼저이 답변 을 참조 하지만 기록을 위해 이해하는대로 다시 설명하겠습니다.

find()메서드 를 사용 하면 Model의 인스턴스가 이미 반환됩니다 (쿼리 빌더가 아님). 이것이 with()find 결과를 사용 하면 데이터베이스에서 새로운 쿼리를 수행 한 다음 get()전체 레코드를 반환하는를 호출하는 반면 호출 first()은 첫 번째 레코드 (ID 별).

나는 당신이 여전히 고수하고 싶다면 이것 대해 갈 방법을 제안 했습니다.find()

  • find()쿼리 다음에 오도록하십시오 (열심히로드 됨). 예:

    $request_form = RequestForm::with(['RequestFormsCheck' => function ($q) {
        $q->orderBy("created_at", "DESC")->with('RequestFormsCheckOptions');
    }])->find(7);
    
  • load()찾기 후 사용 (Lazy loaded)-결과가 표시되고 관련 모델을로드합니다. 예:

    $request_form = RequestForm::find(7)->load(['RequestFormsCheck' => function ($q) {
        $q->orderBy("created_at", "DESC")->with('RequestFormsCheckOptions');
    }]);
    
  • 스틱 전화와 with()최종 결과를 호출하기 전에 전체 쿼리 (일 것). 나는 이후에만 필요,이 그것을 할 수있는 최선의 방법이라고 생각 하나 RequestForm을 한 후 많은 것과 관계

내 일반적인 이해 with()는 쿼리 작성기 에서 작동하므로 with()관련성이 있기 전에 쿼리를 계속 모아야합니다 (이 생각은 업데이트해야 할 수 있음).

Eager Loading 에 대해 더 읽어야 할 수도 있습니다 -in Laravel docs

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

TOP 리스트

  1. 1

    C # 16 진수 값 0x12는 잘못된 문자입니다.

  2. 2

    Matlab의 반복 Sortino 비율

  3. 3

    librosa로 생성 된 스펙트로 그램을 다시 오디오로 변환 할 수 있습니까?

  4. 4

    PhpStorm 중단 점에서 변수 값을 볼 수 없습니다.

  5. 5

    종속 사용자 정의 Lightning 선택 목록 Level2 및 Level3을 설정한 다음 Lightning 구성 요소에서 Level2를 재설정하지만 Level2 캐시 데이터가 저장됨

  6. 6

    Watchdog 큐 이벤트를 사용하는 Python 병렬 스레드

  7. 7

    atob은 인코딩 된 base64 문자열을 디코딩하지 않습니다.

  8. 8

    dev 브랜치에 병합 할 때만 트리거하도록 bitbucket에서 AWS Codebuild로 웹훅을 설정하려면 어떻게해야합니까?

  9. 9

    2 개의 이미지를 단일 평면 이미지로 결합

  10. 10

    Assets의 BitmapFactory.decodeStream이 Android 7에서 null을 반환합니다.

  11. 11

    막대 그래프 위에 선이 표시되지 않음

  12. 12

    Python : 특정 범위를 초과하면 플롯의 선 색상을 변경할 수 있습니까?

  13. 13

    기능 선택을위한 Sklearn Chi2

  14. 14

    Ionic 2 로더가 적시에 표시되지 않음

  15. 15

    EventEmitter <string>의 컨텍스트 'this'가 Observable <string> 유형의 'this'메서드에 할당되지 않았습니다.

  16. 16

    매개 변수에서 쿼리 객체를 선언하는 방법은 무엇입니까?

  17. 17

    openCV python을 사용하여 텍스트 문서에서 워터 마크를 제거하는 방법은 무엇입니까?

  18. 18

    아이디어 Intellij : 종속성 org.json : json : 20180813을 찾을 수 없음, maven에서 org.json 라이브러리를 가져올 수 없음

  19. 19

    일반 메서드에서 클래스 속성에 액세스하는 방법-C #

  20. 20

    식별자는 ORA-06550 및 PLS-00201로 선언되어야합니다.

  21. 21

    함수 호출 사이에 데이터를 저장하는 파이썬적인 방법은 무엇입니까?

뜨겁다태그

보관