【问题标题】:Inspect Model relations检查模型关系
【发布时间】:2013-05-30 11:02:41
【问题描述】:

我正在尝试检查我的Eloquent 模型以了解它们与其他模型的关系。问题是关系被简单地定义为一个单一的方法,并且不存在关系的中心索引:

public function posts()
{
    return $this->hasMany('Post');
}

为了检查所有关系,我需要提取方法列表,取出从Eloquent 继承的那些,执行每个单独的并检查返回类型:

$all = get_class_methods($model);
$inherited = get_class_methods('Eloquent');
$unique = array_diff($all, $inherited);

foreach($unique AS $method)
{
    $relation = $model->$method();
    if(is_a($relation, 'Illuminate\Database\Eloquent\Relations\Relation'))
    {
        //... this is a relation, do something with it
    }
}

不用说,这是非常危险的。有没有办法以不同的、更安全的方式进行这种检查?

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

    您可以将 PHPDoc cmets 添加到您的关系方法中,然后使用 PHP reflection API 从源中提取它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-27
      • 2013-10-07
      • 1970-01-01
      • 2014-01-18
      • 2022-01-26
      • 2010-11-17
      相关资源
      最近更新 更多