首页 > 解决方案 > 在一个维度中连接来自另一个模型的单个列

问题描述

我需要为 datatables.net 提供单维结果。

假设我有这 2 个模型:

客户模型

class CustomerModel extends \sys\Model
{
    public $timestamps = false;

    protected $table = 'Customer';
    protected $primaryKey = 'customerId';

    protected $hidden   = [];
    protected $guarded  = [ 'customerId' ];


    public function paymentMethod(){
        return $this->hasOne('\app\model\PaymentMethodModel' , 'paymentMethodId' , 'paymentMethodId');
    }


    protected $fillable =
    [
       'customerName', 'address'
    ];          

}

付款方式模型

class PaymentMethodModel extends \sys\Model
{
    public $timestamps = false;

    protected $table = 'PaymentMethod';
    protected $primaryKey = 'paymentMethodId';

    protected $hidden   = [];
    protected $guarded  = [ 'paymentMethodId' ];
    protected $fillable =
    [
       'paymentMethodName'
    ];          


}

如果我选择使用 CustomerModel,AgentModel::with(['paymentMethod']); 我会得到:

{
    "customerID": 1,
    "customerName": "John Doe"
    "address": "London"
    "payment_method": 
     {
         "paymentMethodId": 1,
         "paymentMethodName" : "Cash"
     }     
}

我想要实现的是我希望paymentMethodName将结果作为一个平面对象,如下所示:

{
    "customerID": 1,
    "customerName": "John Doe"
    "address": "London"
    "paymentMethodName" : "Cash"  
}

在不使用原始查询的情况下以“Laravel”方式实现这一目标?

标签: laraveleloquent

解决方案


使用 Laravel API 资源是一个很好的用例,它将模型转换为 Api 响应,请在此处阅读文档API 资源

这很简单,从构建你的资源开始,称之为客户资源。这会将您的模型转换为 JSON 响应。如果您为某些遗留代码创建包装器,这也很有用,那么您可以轻松地将模型转换为新结构。

use Illuminate\Http\Resources\Json\JsonResource;

class CustomerResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'customerID' => $request->customerId,
            'customerName' => $request->customerName,
            'address' => $request->address,
            'paymentMethodName' => $request->paymentMethod->paymentMethodName,
        ];
    }
}

然后在您的 API 控制器代码中,您可以像这样使用 API 资源。

return new CustomerResource($customerModel);

这似乎是一项非常少的工作,但是当事情变得复杂时,这是一个可以帮助您很多的解决方案。当您处理多个模型、关系或类似时。这是首选方式,如果人们有兴趣,Fractal 是一个不错的替代方案,因为在制作 API 资源之前,它是一个流行的选择Fractal Documentation


推荐阅读