简体   繁体   English

获取相关模型的类(名称)(Laravel 4,Eloquent)而不检索实例

[英]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. 我还研究了“getRelations()”,它返回一个数组,其中关系functionNames为填充相关项的键,如果没有则返回NULL。

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. 我也可以创建一个新的关系实例,这样我就可以检索它的className而不是保存它。

To be clear I want the className of the object that is returned by the relational function. 要清楚,我想要关系函数返回的对象的className。 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: 要继续上面的代码,执行以下操作将为您提供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 ); $ modelName现在用类本身填充..所以如果你想要className,它应该是get_class($ modelName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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