Eloquent 对关系方法的模型反射
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 class 的 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);
}
调用关系 方法 永远不会 return 模型。它 return 是关系对象。您可以通过访问动态 属性 city
(或调用 getAttribute('city')
)或调用关系方法然后 get()
->city()->get()
.[=17 来获取模型=]
有关 ->city
和 ->city()
的更深入分析,请参阅
在 Select2 版本 4 上,我 运行 遇到了一个让我难过一分钟的问题,希望遇到同样问题的任何人都会发现这个 post 有用。
我一直在使用 "templateSelection",这导致了预先设置 select 值的问题,因为它没有从我的 ajax 响应中返回正确的信息。这是我的修复:
templateSelection: function(repo){
if(typeof repo.name != 'undefined'){
return repo.name;
}
return repo.text;
}
我的 ajax 响应在我的响应中返回了一个 "name" 值,但是当我将一个选项设置为 preselect 时,它返回 "text"。所以我简单的查了一下。
我在通过反射调用模型上的关系方法时遇到问题。我的模型是:
class User extends \Eloquent
{
public function city()
{
return $this->belongsTo('City', 'city_id', 'id');
}
}
class City extends \Eloquent
{
}
当我通过 User class 的 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);
}
调用关系 方法 永远不会 return 模型。它 return 是关系对象。您可以通过访问动态 属性 city
(或调用 getAttribute('city')
)或调用关系方法然后 get()
->city()->get()
.[=17 来获取模型=]
有关 ->city
和 ->city()
的更深入分析,请参阅
在 Select2 版本 4 上,我 运行 遇到了一个让我难过一分钟的问题,希望遇到同样问题的任何人都会发现这个 post 有用。
我一直在使用 "templateSelection",这导致了预先设置 select 值的问题,因为它没有从我的 ajax 响应中返回正确的信息。这是我的修复:
templateSelection: function(repo){
if(typeof repo.name != 'undefined'){
return repo.name;
}
return repo.text;
}
我的 ajax 响应在我的响应中返回了一个 "name" 值,但是当我将一个选项设置为 preselect 时,它返回 "text"。所以我简单的查了一下。