Get all relations name in laravel5 model

↘锁芯ラ 提交于 2020-04-17 07:12:58

问题


I have model include of several relation for example like this:

public function NewsCategory()
{ 
   return $this->belongsTo("News\Model\NewsCategory");
}
public function NewsImage()
{ 
   return $this->belongsTo("News\Model\NewsImage");
}
public function NewsTag()
{ 
   return $this->belongsTo("News\Model\NewsTag");
}

and relations create dynamically.
How can I get all this class name? In this example I want
NewsCategory,NewsImage,NewsTag


回答1:


one approach is to as follows :

$results = ModelClass::where(x,y)->with(['NewsCategory','NewsImage','NewsTag'])->first();

then you can use getRelations();

$relationshipKeys = array_keys($results->getRelations());



回答2:


$model_specific_method_name_array = array_diff(get_class_methods(<YourMOdel>), get_class_methods(<AnotherDummyEloquentModelWithoutAnyMethods>));

Then remove other known methods on your model from array.



来源:https://stackoverflow.com/questions/37896955/get-all-relations-name-in-laravel5-model

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