【问题标题】:Laravel relationship with custom methodLaravel 与自定义方法的关系
【发布时间】:2019-03-22 02:14:29
【问题描述】:

表项目:

project_id (int)
requestor_id (uuid)

表请求者:

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);
}

选择所有具有请求者关系的项目:

$query = (new Project)->newQuery()->with(['requestor'])->get();

问题是: 如何选择所有具有请求者关系的项目以及在每个请求者对象调用方法 getLdapAttribute 并将所有项目作为一个对象返回?

非常感谢:)

【问题讨论】:

  • 您的任何代码与 sql 有什么关系??

标签: sql laravel ldap relationship


【解决方案1】:

您可以将“Ldap”属性的名称放在 App\Requestor 类的 $appends 数组中,Eloquent 会自动将名为 ldap 的属性附加到 getLdapAttribute 方法返回的值中。

Link to the Official Laravel Documentation for this Eloquent feature !

【讨论】:

    【解决方案2】:

    由于没有指定getLdapAttribute方法的SQL查询,我们可以先获取项目,然后迭代获取该属性。

    如果给出getLdapAttribute的SQL查询,那么我们可以在一个查询中获取所有数据(这里我们在获取项目的第一个查询之后获取属性)。

    $projects = Project::with(['requestor'])
    ->get()
    ->each(function ($project) {
        $project->requestor->getLdapAttribute();
    });
    

    【讨论】:

    • 是的,我首先使用了这个解决方案,但上面的 Diego 提出了更好的建议 :) 但也谢谢你。
    猜你喜欢
    • 2019-02-09
    • 2018-06-12
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 2017-07-15
    • 2018-10-16
    • 2016-11-01
    • 2021-04-04
    相关资源
    最近更新 更多