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

时间:2014-01-13 09:54:02

标签: php laravel eloquent

$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。所以在这个例子中它可能是香蕉。

1 个答案:

答案 0 :(得分:2)

好的发现了。结果很简单。要继续上面的代码,执行以下操作将为您提供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);