![](/img/trans.png)
[英]Laravel Eloquent Model change table name on runtime in a related instance
[英]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
我还研究了“getRelations()”,它返回一个数组,其中关系functionNames为填充相关项的键,如果没有则返回NULL。
我也可以创建一个新的关系实例,这样我就可以检索它的className而不是保存它。
要清楚,我想要关系函数返回的对象的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现在用类本身填充..所以如果你想要className,它应该是get_class($ modelName);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.