Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all relationships from Eloquent model

Having one Eloquent model, is it possible to get all its relationships and their type at runtime?

I've tried taking a look at ReflectionClass, but I couldn't find anything useful for this scenario.

For example, if we have the classic Post model, is there a way to extract relationships like this?

- belongsTo: User
- belongsToMany: Tag
like image 714
Manuel Pedrera Avatar asked Dec 02 '13 18:12

Manuel Pedrera


People also ask

What is with () in Laravel?

with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.

What is BelongsTo in Laravel?

BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.

Is eloquent an ORM?

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.


1 Answers

To accomplish this, you will have you know the names of the methods within the model - and they can vary a lot ;)

Thoughts:

  • if you got a pattern in the method, like relUser / relTag, you can filter them out

  • or loop over all public methods, see if a Relation object pops up (bad idea)

  • you can define a protected $relationMethods (note: Laravel already uses $relations) which holds an array with method.

After calling Post->User() you will receive a BelongsTo or 1 of the other objects from the Relation family, so you can do you listing for the type of relation.

[edit: after comments]

If the models are equipped with a protected $with = array(...); then you are able to look into the loaded relations with $Model->getRelations() after a record is loaded. This is not possible when no record is loaded, since the relations aren't touched yet.

getRelations() is in /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php

But currently it doesn't show up in the api at laravel.com/api - this is because we got newer version

like image 178
Rob Gordijn Avatar answered Oct 14 '22 20:10

Rob Gordijn