[英]How can i get relationship type at Laravel
I have a problem like that i wanna write my own form builder at custom project with 70 models but i need to learn relationship type at eloquent and also 2 or 3 depht more. 我有一个问题,我想在70个模型的自定义项目中编写我自己的表单生成器,但我需要在eloquent学习关系类型,还需要2或3个depht。
For example: 例如:
class Category extends BaseModel
{
public function details()
{
return $this->hasMany(CategoryDetail::class);
}
}
class CategoryDetail extends BaseModel
{
public function extras()
{
return $this->morphMany(Extra::class,'model');
}
}
I need something like that: 我需要这样的东西:
learnMethodType(Category::class,'details');
Real need : data comes from builded json 真正需要:数据来自建立的json
learnMethodType(Category::class,'details.extras');
return should be like: 返回应该像:
['model'=> CategoryDetail::class,'type'=>'hasMany', ... other parameters];
['model'=> Extra::class,'type'=>'morphMany', 'name'=> 'model'];
What about this implementation? 这个实现怎么样?
function learnMethodType($classname,$method){
$oReflectionClass = new ReflectionClass($classname);
$method = $oReflectionClass->getMethod($method)
$type = get_class($method->invoke($classname))
return $type;
}
Or simply this: 或者只是这个:
function learnMethodType($classname,$method){
$obj = new $classname;
$type = get_class($obj->{$method}())
return $type;
}
For your case you can also add 对于您的情况,您也可以添加
function get_short_class($obj){
return (new \ReflectionClass($obj))->getShortName();
}
And replace get_class with get_short_class above. 并用上面的get_short_class替换get_class。
Some benchmarks in case you are worried about the reflection class: 一些基准测试 ,以防您担心反射类:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.