Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent

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

  • id
  • file_group_id
  • ... many more

Contacts

  • id
  • file_group_id
  • ...many more

FileGroups

  • id
  • title

Files

  • id
  • file_group_id
  • path

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!

Last updated 3 years ago.
0

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?

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.