Laravel get class name of related model

半城伤御伤魂 提交于 2021-01-16 05:08:13

问题


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');
    }
}

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.


回答1:


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


来源:https://stackoverflow.com/questions/26292718/laravel-get-class-name-of-related-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!