2014-10-10 810 views
15

在我的Laravel应用程序中,我有一个Faq模型。一个Faq模型可以包含很多Product车型,所以Faq类包含以下功能:Laravel获取相关模型的类名称

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

在控制器,我想能够检索定义关系类的名称。举例来说,如果我有一个Faq对象,像这样:

$faq = new Faq(); 

我怎么能确定的关系,在这种情况下会Product的类名。目前我能做到这一点是这样的:

$className = get_class($faq->products()->get()->first()); 

不过,我不知道是否有做到同样的事情,而无需实际运行查询的方式。

回答

38

是的,有一种方式来获得相关的模型,而无需查询:

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

它将为所有关系的工作。

这将返回全名和命名空间。如果你想要的基地名称使用:

// laravel helper: 
$baseClass = class_basename($className); 

// generic solution 
$reflection = new ReflectionClass($className); 
$reflection->getShortName(); 
+0

getRelated是一个伟大的发现!以前我使用$ className = get_class($ faq-> products() - > getQuery() - > getModel()); – malhal 2015-08-06 23:06:54

0

我认为你不能那样做。我不知道你需要它,但你可以简单地增加,你把你所有的关系类的名称,并在那里你回到一个你想要额外的方法:

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

使用PHPReflection API您可以尝试这个:写在这个格式在你的类

$class = new ReflectionClass('Faq'); 
$method = $class->getMethod('products'); 
$startLine = $method->getStartLine(); 
$endLine = $method->getEndLine(); 
$length = $endLine - $startLine; 

$fileName = $class->getFileName(); 
if(!empty($fileName)) { 
    $fileContents = file($fileName); 
    $methodSource = trim(implode('',array_slice(file($fileName),$startLine,$length))); 
    preg_match('/\((.*)\)/', $methodSource, $m); 
    $className = $m[1]; // <-- This is the result 
} 

您的方法必须:

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

顺便说一句,这是必要做的呢?大概你可以用Marcin Nabiałek的简单而简单的答案,我只是在周围玩。