【问题标题】:Get all relations name in laravel5 model获取 laravel5 模型中的所有关系名称
【发布时间】:2016-10-20 04:47:58
【问题描述】:

我有几个关系的模型包括,例如:

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

关系是动态创建的。
我怎样才能得到所有这些类名? 在这个例子中我想要
NewsCategory,NewsImage,NewsTag

【问题讨论】:

标签: php laravel laravel-5 laravel-5.2 relationship


【解决方案1】:

一种方法如下:

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

然后你可以使用 getRelations();

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

【讨论】:

    【解决方案2】:
    $model_specific_method_name_array = 
        array_diff(
            get_class_methods(<YourModel>), 
            get_class_methods(<AnotherDummyEloquentModelWithoutAnyMethods>)
        );
    

    然后从数组中删除模型上的其他已知方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      • 1970-01-01
      • 2015-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多