vendredi 3 décembre 2021

Laravel constrain eager loading - apply limit if relationship column != 1

Am building a system that works similar to the popular flashcard software called "Anki" and am trying to eager load some answers that belong to a user study, but with some modifications.

Model relationships

  • User has many Study
  • Study has many Answer

Here is the code snippet. (Take a look at the second section below)

$user_query = User::with([
    'studies.answers' => function ( $query_answer ) use ( $args ) {
        $query_answer
            ->where( 'grade', '=', 'hold' )
            ->groupBy( 'card_id' )
            ->orderByDesc( 'id' );

            if ( $args['no_date_limit'] ) {
                $query_answer = $query_answer->where( 'next_due_at', '>', $args['start_date'] );
            } else {
                $query_answer = $query_answer->whereBetween( 'next_due_at', [ $args['start_date'], $args['end_date'] ] );
            }

            if ( ! empty( $args['card_ids_in'] ) ) {
                $query_answer = $query_answer->whereIn( 'card_id', $args['card_ids_in'] );
            }
            if ( ! empty( $args['card_ids_not_in'] ) ) {
                $query_answer = $query_answer->whereNotIn( 'card_id', $args['card_ids_not_in'] );
            }

Below, I want to apply the limit if study.answer_all_on_hold ($study_all_on_hold) != 1 And also read the $no_on_hold value from study.no_on_hold

            // Here, I want to apply the limit ($study_all_on_hold ) if study.answer_all_on_hold != 1
            if ( ! $study_all_on_hold ) {
                // And also read the $no_on_hold value from study.no_on_hold
                $query_answer = $query_answer->limit( $no_on_hold );
            }
        },
    ])
    ->where( 'ID', '=', $user_id );

As you can see am trying to apply the limit from the column value of the study. Is this currently possible ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire