检查模型关系

时间:2013-05-30 11:02:41

标签: laravel laravel-4 eloquent

我正在尝试检查我的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
    }
}

毋庸置疑,这非常危险。有没有办法以不同的,更安全的方式进行这种检查?

1 个答案:

答案 0 :(得分:0)

您可以将PHPDoc注释添加到关系方法中,然后使用PHP reflection API从源中提取这些注释。