samedi 2 janvier 2016

Get nested with on related models

I am making a test preparation platform and want to get all answered questions by the user.

The query should return:

  • User Questions through Model
  • Related Question Model with fields
  • Question should return with the category it belongs to

Query:

    $user = User::where('id', '=', $user_id)->first();

    $completed_questions = $user->user_questions()->with(['question' => function ($q) {
        $q->with('category');
    }])->get();

When I make a test GET request, the User_Question and nested Question models are returned. But the nested Category within Question is null.

Models:

User:

public function questions()
{
    return $this->hasMany('App\Question');
}

public function user_questions()
{
    return $this->hasMany('App\UserQuestion');
}

Category:

...
public function questions()
{
    return $this->hasMany('App\Question');
}

Question:

public function user()
{
    return $this->belongsToMany('App\User');
}

public function category()
{
    return $this->belongsTo('App\Category');
}

User Question:

public function user()
{
    return $this->belongsTo(User::class);
}

public function question()
{
    return $this->belongsTo(Question::class);
}

On table creation, I create foreign keys:

    Schema::table('question_user', function(Blueprint $table)
    {
        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('question_id')->references('id')->on('questions');
    });

    Schema::table('questions', function(Blueprint $table)
    {
        $table->foreign('image_id')->references('id')->on('images');
        $table->foreign('cat_id')->references('id')->on('categories');
    });



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire