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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With