Home > Back-end >  How to obtain three level model data laravel
How to obtain three level model data laravel

Time:07-25

Updated

User model

class User extends Authenticatable
{
    use HasFactory, Notifiable, HasApiTokens, HasRoles;

    const MALE = 'male';
    const FEMALE = 'female';

    protected $guard_name = 'sanctum';


    public function educationalBackgrounds()
    {
        return $this->hasMany("App\Models\Users\EducationalBackground", "user_id");
    }

    public function seminars()
    {
        return $this->hasMany("App\Models\Users\Seminar", "user_id");
    }
}

I have child table EducationalBackground which is related to User table

class EducationalBackground extends Model
{
    use HasFactory;

    protected $table = 'users.educational_backgrounds';
    protected $fillable = [
        'user_id',
        'studies_type',
        'year',
        'course',
    ];

    public function user()
    {
        return $this->belongsTo('App\Models\User', 'user_id');
    }

    public function educationalAwards()
    {
        return $this->hasMany("App\Models\Users\EducationalAward", "educational_background_id");
    }
}

And a third table that i want to access the award field

class EducationalAward extends Model
{
    use HasFactory;

    protected $table = 'users.educational_awards';
    protected $fillable = [
        'educational_background_id',
        'award',
        'photo',
    ];

    public function educationalBackground()
    {
        return $this->belongsTo('App\Models\Users\EducationalBackground', 'educational_background_id');
    }
}

I have api get route here

Route::get('/educational-background/{id}', [UserProfileController::class, 'getEducationalBackground']);

Here is my api method it works fine. But i want to go deeper and access the data of third table.

public function getEducationalBackground($id) 
    {
        $educationalBackground = EducationalBackground::with('user')->where('user_id', $id)->get();

        return response()->json($educationalBackground, 200);
    }

CodePudding user response:

It looks like you're not really grasping the concept of relations yet. Also, I'd advise you to look into route model binding :) What you basically want to be doing is:

public function getEducationalBackground($id) 
{
    $user = User::find($id);
    return $user->educationalBackgrounds()->with('educationalAwards')->get();
}

Also, when you're pretty sure that whenever you want to use backgrounds, you also want to use the awards, you can add the with(...) to the model definition like so:

class EducationalBackground extends Model
{
    ...
    protected $with = ['educationalAwards'];
}

That way, you can simplify your controller method to:

public function getEducationalBackground($id) 
{
    $user = User::find($id);
    return $user->educationalBackgrounds;
}
  • Related