gpt4 book ai didi

php - 在不检索实例的情况下获取相关模型(Laravel 4,Eloquent)的类(名称)

转载 作者:搜寻专家 更新时间:2023-10-31 21:10:27 25 4
gpt4 key购买 nike

$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()”,它返回一个数组,其中关系函数名称作为填充相关项的键,如果没有则返回 NULL。

我也可以创建一个新的关系实例,这样我就可以检索它的类名而不是保存它。

明确地说,我想要关系函数返回的对象的类名。所以在这个例子中它可能是香蕉。

最佳答案

好的,找到了。结果很简单。从上面的代码继续,执行以下操作将为您提供类名:

$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 );

关于php - 在不检索实例的情况下获取相关模型(Laravel 4,Eloquent)的类(名称),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21088205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com