Laravel 获取相关模型的类名

2021-12-26 00:00:00 php laravel eloquent

在我的 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();

相关文章