Mohsin Younas
Mohsin Younas

Reputation: 374

Lazy Eager Loading for third level relationship in Laravel

UserModel has many lead and each lead can have one propertyLead and each propertyLead can have many attachments. Each model is listed below,

UserModel:

  public function leads()
{
    return $this->hasMany('App\Models\Leads', 'fk_user_id');
}

LeadsModel:

    public function propertyLead()
{
    return $this->hasOne('App\Models\PropertyLead', 'fk_lead_id');
}

PropertyLeadModel:

    public function attachments()
{
    return $this->hasMany('App\Models\Attachments', 'fk_property_lead_id');
}

Now, I am using the Lazy Eager Loading of laravel to readData from dataBase, so far I am able to reach to PropertyLeadModel but I am not able to understand how to reach to attachment relation in the PropertyLeadModel,

$leads = User::find(Auth::user()->id)->leads->load('propertyLead');

so user gives me leads and leads gives me propertyLead but not able to understand how to reach more down to Attachments in the propertyLeadModel.

Please, help me to understand. Thank you.

Upvotes: 0

Views: 691

Answers (3)

VIKAS KATARIYA
VIKAS KATARIYA

Reputation: 6005

Try this

User::with('leads.propertyLead.attachments')->where('id',Auth::user()->id)->first();

Upvotes: 2

patricus
patricus

Reputation: 62268

You can load nested relationships using "dot" notation.

$user = Auth::user();
$user->load('leads.propertyLead.attachments');

// see all relationships loaded
dd($user);

Since leads and attachments are "many" relationships, they will be Collections you have to iterate through to access any particular instance.

Upvotes: 3

Ratto
Ratto

Reputation: 178

Try this, not tested

$leads = Auth::user()->leads->load('propertyLead', 'propertyLead.attachments');

Upvotes: 1

Related Questions