Michael Cordingley
Michael Cordingley

Reputation: 1525

Eloquent Eager Load Double Relationship

This one's been bothering me and Google hasn't been of any help. I have two models, a Dance model and an Author model. The relationship is that an author can have many dances. The wrinkle is that there are actually two relationships between these objects, as there is the original author and an author much later credited with reconstructing the dance (these are historical dances, after all). I can eager load with the load() function for the relation that uses the normal foreign key, but I cannot find out how to eager load the relation that uses a differently-named foreign key.

How do I do eager loading on this second relation?

Upvotes: 1

Views: 1771

Answers (2)

Orici
Orici

Reputation: 431

You can do this:

$dance = ModelName::query()
    ->with('eagerNameOne')
    ->with('eagerNameTwo')
    ->find($id);

where ::query() was added only tu put all the eagers on the same identation level.

Upvotes: 0

Kylie
Kylie

Reputation: 11749

When setting up a relationship with a different foreign key you have to specify in the relationship which key you wanna use...return $this->hasOne('Author', 'foreign-key');

So if I understand your question you wanna setup a relationship to two authors, in the same author table....

So maybe something like this then?? (replace foreign_key with your table field)

public function orig_author(){
 return $this->hasOne('Author');
}

public function second_author(){
 return $this->hasOne('Author', 'foreign-key');
}

public function dance(){
return $this->hasMany('Dance');
}

Then just retrieve it like so...($id being the id of your dance)

$dance = Dance::with('orig_author','second_author')->find($id);

But to be honest, I've never tried having a double relationship with a table.....let me know if it works out for you. :) Id be very interested.

Upvotes: 1

Related Questions