Laravel 获取每个相关模型的方法 return 值

Laravel Get method return value for each related model

我有一个 Client 模型,它与 Location 模型有 hasMany 关系。在我的 Location 模型中,我有一个 status() 方法,它 return 是一个数组。

在我的 ClientController 中,我正在获取客户端模型,然后获取所有相关的位置,但我还想包含数组 returned 来自附加到每个位置的 status 方法.我不确定该怎么做。我确定我可以通过在每个位置使用 foreach 循环来做到这一点,但我想知道是否有一种“eloquent”的方法。

这是我的客户端控制器:

    public function show($id)
    {
        $client = Client::findOrFail($id);        
        
        $locations = $client->locations()->withTrashed()->get();

        //foreach($locations as $location)
        //{
         //   print_r($location->status());
        //}


        return view('pages.clients.show')
            ->with('client', $client)
            ->with('locations', $locations)
    }

这是我的位置模型方法:

    public function status()
    {
        $result = array();

        if($this->deleted_at)
        {
           $result['color'] = 'danger';
           $result['value'] = 'Inactive';
        }
        elseif($this->is_onboarding_completed)
        {
            $result['color'] = 'success';
            $result['value'] = 'Active';
        }
        else
        {
            $result['color'] = 'warning';
            $result['value'] = 'Onboarding';
        }

        return $result;
    }

我的位置关系:

    public function client()
    {
        return $this->belongsTo(Client::class);
    }

我的客户关系:

    public function locations()
    {
       return $this->hasMany(Location::class);
    }

另外,我想知道 if/how 我可以 return 位置自动 return 状态。我知道我可以使用 protected $with = []; 对位置执行此操作,但是当我尝试包含非关系时出现错误。

此外,如果有更好的方法,欢迎任何设计改进。

正如@lagbox在评论区所说,你需要一个accessor.

位置模型:

public function getStatusAttribute()
{
    $result = [];

    if($this->deleted_at)
    {
        $result['color'] = 'danger';
        $result['value'] = 'Inactive';
    }
    elseif($this->is_onboarding_completed)
    {
        $result['color'] = 'success';
        $result['value'] = 'Active';
    }
    else
    {
        $result['color'] = 'warning';
        $result['value'] = 'Onboarding';
    }

    return $result;
}

控制器:

public function show($id)
{
    $client = Client::findOrFail($id);        
    $locations = $client->locations()->withTrashed()->get();

    foreach($locations as $location)
    {
       dd($location->status);
    }

    ...
}