Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

php - Laravel Eloquent Relationship: How to get parent of parent information from child using Laravel eloquent model relationship?

I am facing a problem getting a query result in Laravel Controller. Let me describe to you..

I have three models in Laravel Project ModelA, ModelB, ModelC.

The tables look like this:

  1. Table for ModelA:

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Problem solved

My Solution:

My code in ModelC Controller:

$data = ModelC::with('modelB')->get();

Relation function in ModelB:

public function modelA(){
    return $this->belongsTo(ModelA::class);
}

Relation function in ModelC:

public function modelB(){
    return $this->belongsTo(ModelB::class)->with('modelA');
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...