php Laravel 获取相关模型的类名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26292718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:15:56  来源:igfitidea点击:

Laravel get class name of related model

phplaraveleloquent

提问by flyingL123

In my Laravel application I have an Faqmodel. An Faqmodel can contain many Productmodels, so the Faqclass contains the following function:

在我的 Laravel 应用程序中,我有一个Faq模型。一个Faq模型可以包含多个Product模型,因此Faq该类包含以下函数:

class Faq extends Eloquent{ 
    public function products(){
        return $this->belongsToMany('Product');
    }
}

In a controller, I would like to be able to retrieve the class name that defines the relationship. For example, if I have an Faqobject, like this:

在控制器中,我希望能够检索定义关系的类名。例如,如果我有一个Faq对象,如下所示:

$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:

我如何确定关系的类名,在这种情况下是Product. 目前我可以这样做:

$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.

但是,我想知道是否有一种方法可以在无需实际运行查询的情况下完成同样的事情。

回答by Jarek Tkaczyk

Yes, there is a way to get related model without query:

是的,有一种无需查询即可获取相关模型的方法:

$className = get_class($faq->products()->getRelated());

It will work for all relations.

它适用于所有关系。

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

回答by Marcin Nabia?ek

I think you cannot do that. I don't know what you need it for, but you could simply add extra method where you put all your relations class name and where you return one you want:

我认为你不能那样做。我不知道你需要它做什么,但你可以简单地添加额外的方法,在其中放置所有关系类名并返回你想要的类名:

public function getRelationsClassName($relation) {
    $relations = [
        'products' => 'Product',
        'users' => 'User',
    ]  
    return isset($relations[$relation]) ? $relations[$relation] : null;
}