简体   繁体   中英

Getting the class(name) of a related model (Laravel 4, Eloquent) without retrieving an instance

$relationFunctionName = 'bananas';    //this is set dynamically at runtime, and is always a relation function
$currentClass         = 'FruitBowl'; //this is set dynamically at runtime, and is always an Eloquent Model
$rowId                = 1; //this is also set dynamically at runtime

$grabber              = new $currentClass();
$item                 = $grabber->with($relationFunctionName)->find($rowId);
$relatedItem          = $item->{$relationFunctionName};

exit( get_class( $relatedItem ) );
// returns the className of the related item (if there is one) returns the current class if there is none

I also looked into "getRelations()" which returns an array with the relational functionNames as keys filled with the related items or NULL if there are none.

I could also do with creating a new instance of the relation, so that I can retrieve the className of it and not save it.

To be clear I want the className of the object that is returned by the relational function. So in this example it would probably be Banana.

Ok found it. Turns out to be pretty simple. To continue from the code above, doing the following will give you the className:

$relationFunctionName = 'bananas';    //this is set dynamically at runtime, and is always a relation function
$currentClass         = 'FruitBowl'; //this is set dynamically at runtime, and is always an Eloquent Model
$rowId                = 1; //this is also set dynamically at runtime

$grabber              = new $currentClass();
$modelName            = $grabber->{$relationFunctionName}()->getModel();

$modelName is now filled with the class itself.. so if you want the className it should be get_class( $modelName );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM