【问题标题】:Get custom relationship data with Eloquent query builder使用 Eloquent 查询构建器获取自定义关系数据
【发布时间】:2023-04-02 10:57:01
【问题描述】:

我有这个问题:

FHINotification::with(['log'])
    ->where('user', $user->getSAMAccountName())
    ->whereNull('read_at')
    ->get();

“Log”模型具有获取自定义数据的功能(比数据库中的数据更具可读性)

public function getData(): array
{
    Game::setWithoutStandardEdition(true);
    $ldapService = App::make('App\Services\LdapService');
    $log['url'] = $this->getUrl($this->task->resourceable_type, $this->task->string_resourceable_id);
    $log['action'] = $this->getActionName($this->action);
    $log['resource_name'] = $this->getResourceName($this->task->resourceable);
    $log['user'] = $ldapService->getUserByUsername($this->user)->getDisplayName();

    return $log;
}

我可以从 Log 实例调用此方法,例如:$log->getData() 但是否可以从查询生成器调用它? 如果没有,我必须循环我的查询结果来格式化它们中的每一个。

谢谢你:)

【问题讨论】:

    标签: laravel eloquent relationship builder eager-loading


    【解决方案1】:

    如果你总是想把你的日志转换成这个,你可以通过覆盖你模型的 toArray 函数来使用它:

    public function toArray(): array
    {
        Game::setWithoutStandardEdition(true);
        $ldapService = App::make('App\Services\LdapService');
        $log['url'] = $this->getUrl($this->task->resourceable_type, $this->task->string_resourceable_id);
        $log['action'] = $this->getActionName($this->action);
        $log['resource_name'] = $this->getResourceName($this->task->resourceable);
        $log['user'] = $ldapService->getUserByUsername($this->user)->getDisplayName();
    
        return $log;
    }
    

    如果你有一个日志实例,你可以这样做:

    $log->toArray(); 
    

    或者当有一个 FHINotification 集合时:

    $FHINotification_collection->toArray();
    

    然后您的日志将使用您的自定义 toArray() 函数转换为数组

    如果你想从你的对象中访问你的属性,而不是将它转换成一个数组,那么你应该使用访问器:

    public function getUrlAttribute()
    {
        Game::setWithoutStandardEdition(true);
        $ldapService = App::make('App\Services\LdapService');
        return $this->getUrl($this->task->resourceable_type, $this->task->string_resourceable_id);
    }
    

    你的每个属性等等

    那么你就可以使用它了:

    $log->url

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-29
      • 2021-03-21
      • 1970-01-01
      • 2015-01-24
      • 2018-12-04
      • 2017-03-30
      • 1970-01-01
      • 2016-09-28
      相关资源
      最近更新 更多