laravel - 在一个维度中连接来自另一个模型的单个列
问题描述
我需要为 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”方式实现这一目标?
解决方案
使用 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。
推荐阅读
- oop - 将方法分解为子方法可以称为OOP抽象吗?
- php - VPS 上的 WordPress 安装 - 不在域上加载 CSS,仅在 IP 地址上加载
- r - 如果修复错误怎么办:threefry.h:Docker中没有这样的文件或目录?
- node.js - fs.readDirSync 在打字稿中找不到目录?
- r - 如何将年份填充到 R 中的数据框列表中
- python - 在 Python 中计算 Pearson 的标准化残差
- ajax - 通过 WP REST API 创建评论时的电子邮件通知
- java - 如何删除尾随零?
- c++ - 如何在不知道维度的情况下在二维数组中输入
- php - Add a class to get_the_term_list output