关系方法上的显式模型反射


Eloquent model reflection over a relation method

在反射模型上调用关系方法时遇到问题。我的型号是:

class User extends 'Eloquent
{
    public function city()
    {
        return $this->belongsTo('City', 'city_id', 'id');
    }
}
class City extends 'Eloquent
{
}

当我在User类的ReflectionMethod实例上调用city方法时,我不会得到city模型。我认为问题与Eloquent懒惰加载有关,但我无法理解这个问题:(有什么想法吗?

提前感谢您的回答!

更新:

我的反射码:

$rc = new 'ReflectionClass($model);
if ($rc->hasMethod($fieldName)) {
    // This two calls below are returning: "Relationship method must return 
    // an object of type Illuminate'Database'Eloquent'Relations'Relation"
    $relation = $rc->getMethod('getAttribute')->invoke($model, $fieldName);
    $rc->getMethod($fieldName)->invoke($model);
    // And this one is returning: "Property city does not exist"
    $rp = $rc->getProperty($fieldName);
}

调用relationship方法将永远不会返回模型。它返回关系对象。您可以通过访问动态属性city(或调用getAttribute('city'))或通过调用关系方法,然后调用get() ->city()->get()来获取模型。

有关->city->city()的更深入分析,请参阅我在上的回答

在Select2版本4上,我遇到了一个让我困惑了一分钟的问题,希望任何遇到同样问题的人都会觉得这篇文章很有帮助。

我一直在使用"templateSelection",这导致了预先设置select值的问题,因为它没有从我的ajax响应中返回正确的信息。这是我的解决方案:

templateSelection: function(repo){
    if(typeof repo.name != 'undefined'){
        return repo.name;
    }
    return repo.text;
}

我的ajax响应在响应中返回了一个"name"值,但当我设置一个选项进行预选时,它返回的是"text"。所以我只是检查了一下。