問題描述
在我的 Laravel 應用程序中,我有一個 Faq
模型.一個 Faq
模型可以包含多個 Product
模型,所以 Faq
類包含以下函數:
In my Laravel application I have an Faq
model. An Faq
model can contain many Product
models, so the Faq
class contains the following function:
class Faq extends Eloquent{
public function products(){
return $this->belongsToMany('Product');
}
}
在控制器中,我希望能夠檢索定義關系的類名.例如,如果我有一個 Faq
對象,如下所示:
In a controller, I would like to be able to retrieve the class name that defines the relationship. For example, if I have an Faq
object, like this:
$faq = new Faq();
如何確定關系的類名,在本例中為 Product
.目前我可以這樣做:
How can I determine the class name of the relationship, which in this case would be Product
. Currently I am able to do it like this:
$className = get_class($faq->products()->get()->first());
但是,我想知道是否有一種方法可以在無需實際運行查詢的情況下完成同樣的事情.
However, I'm wondering if there is a way to accomplish this same thing without having to actually run a query.
推薦答案
是的,有一種不用查詢就可以得到相關模型的方法:
Yes, there is a way to get related model without query:
$className = get_class($faq->products()->getRelated());
它適用于所有關系.
這將返回帶有命名空間的全名.如果您只想使用基本名稱:
This will return full name with namespace. In case you want just base name use:
// laravel helper:
$baseClass = class_basename($className);
// generic solution
$reflection = new ReflectionClass($className);
$reflection->getShortName();
這篇關于Laravel 獲取相關模型的類名的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!