Hello everyone!
I am trying to achieve something like a morph relation but in a different manner. I don't like the database structure that the Eloquent's morph functionality forces and I am trying to do it "the opposite way". My DB structure is:
Orders
Contacts
FileGroups
Files
As you can see Contact and Orders can have both a FileGroup attached to them.
Here is my FileGroup model:
class FileGroup extends Eloquent {
protected $guarded = array('id');
public function files() {
return $this->hasMany('File');
}
public function order() {
return $this->hasOne('Order');
}
public function contact() {
return $this->hasOne('Contact');
}
public function attachee() {
if ( $this->order ) {
return $this->order();
}
if ( $this->contact ) {
return $this->contact();
}
return $this;
}
}
What I am trying to do here is the "attachee" method. I guess you can get an idea what I am trying to do, but I am obviously doing it the wrong way. I just want attachee() to return either an Order, a Contact, or nothing, depending on whether the FileGroup is attached to any of these. I don't think Eloquent has a built-in mechanism for achieving this. How would you recommend me to approach? Thank you for your help!
Well keep in mind that the file_group_id can exist in both the contacts and orders table since your db structure isn't preventing that. Hopefully your code is preventing that. Your code looks like it should work. What's wrong with it?
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community