Laravel 与自定义方法的关系
Laravel relationship with custom method
Table 项目:
project_id (int)
requestor_id (uuid)
Table 请求者:
requestor_id (uuid)
模型项目:
public function requestor() {
return $this->hasOne('App\Models\Requestor', 'requestor_id', 'requestor_id');
}
模型请求者有一种方法:
// this method return object users info from ldap
public function getLdapAttribute() {
$ldapWrapper = new LdapWrapper();
return $ldapWrapper->checkIfUuidExists($this->requestor_id, true);
}
Select 有请求者关系的所有项目:
$query = (new Project)->newQuery()->with(['requestor'])->get();
而问题是:
我怎样才能 select 所有具有请求者关系的项目以及每个请求者对象调用方法 getLdapAttribute 和 return 都作为一个对象?
非常感谢:)
由于没有指定SQL查询getLdapAttribute
方法,我们可以先fetch projects,然后遍历得到那个属性。
如果SQL查询getLdapAttribute
那么我们可以在一个查询中获取所有数据(这里我们在第一次查询获取项目后获取属性)。
$projects = Project::with(['requestor'])
->get()
->each(function ($project) {
$project->requestor->getLdapAttribute();
});
您可以将 "Ldap" 属性的名称放入 App\Requestor Class 的 $appends 数组中,Eloquent 将自动附加一个 属性使用为 getLdapAttribute 方法返回的值 命名为 ldap。
Link to the Official Laravel Documentation for this Eloquent feature !
Table 项目:
project_id (int)
requestor_id (uuid)
Table 请求者:
requestor_id (uuid)
模型项目:
public function requestor() {
return $this->hasOne('App\Models\Requestor', 'requestor_id', 'requestor_id');
}
模型请求者有一种方法:
// this method return object users info from ldap
public function getLdapAttribute() {
$ldapWrapper = new LdapWrapper();
return $ldapWrapper->checkIfUuidExists($this->requestor_id, true);
}
Select 有请求者关系的所有项目:
$query = (new Project)->newQuery()->with(['requestor'])->get();
而问题是: 我怎样才能 select 所有具有请求者关系的项目以及每个请求者对象调用方法 getLdapAttribute 和 return 都作为一个对象?
非常感谢:)
由于没有指定SQL查询getLdapAttribute
方法,我们可以先fetch projects,然后遍历得到那个属性。
如果SQL查询getLdapAttribute
那么我们可以在一个查询中获取所有数据(这里我们在第一次查询获取项目后获取属性)。
$projects = Project::with(['requestor'])
->get()
->each(function ($project) {
$project->requestor->getLdapAttribute();
});
您可以将 "Ldap" 属性的名称放入 App\Requestor Class 的 $appends 数组中,Eloquent 将自动附加一个 属性使用为 getLdapAttribute 方法返回的值 命名为 ldap。
Link to the Official Laravel Documentation for this Eloquent feature !