问题描述
在我的Laravel应用程序中,我有一个 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();
如何确定关系的类名,在这种情况下为产品
。目前,我可以这样做:
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获取相关模型的类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!