Question

If I have an Eloquent model defined in my application which has a number of different relationships set up with other model types, how can I get information all of those relationships without knowing anything else about the model I'm dealing with?

For example, imagine a simple Transaction model which can have many Lines and also belong to a single User.

Now, given an instance of the Transaction model (either populated or unpopulated), how can I find out about the relationships it has to the other models?

Just to be clear, I don't want to retrieve the actual related data, I just want to find out what class each relationship refers to and whether it is one to many, many to many etc.

Any advice appreciated.

Thanks

Was it helpful?

Solution

Laravel's eloquent models do not work this way, relationships are defined by methods within the model and are not automagically loaded by the model upon instantiation, hence the requirement to actually call these methods when you want to use a specific relationship.

When you instantiate a models class it has zero relationships defined. This can be shown by the following:

$user = new User();

print_r($user->getRelations());

//Output : empty array

As you can see the model is blissfully unaware of any relationships it may or may not have declared in relationship methods. When you call a models relationship:

$user = new User();

$user->find(1)->roles()->get();

Eloquent sets the relationship on the model using a method setRelation($relation, $value) that takes the name of the method called as the first argument and the return of that method as the second. Thus providing the context for the relationship that does not exist before you specifically ask for it.

I know this is not what you're hoping to hear but there is no way to do this with Eloquent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top