Laravel get class name of related model(Laravel 获取相关模型的类名)
问题描述
在我的 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 获取相关模型的类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel 获取相关模型的类名


- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- PHP - if 语句中的倒序 2021-01-01