簡體   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

我還研究了“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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM