如何加入 Laravel 中模型的输出?

How to join output of models in Laravel?

我有以下代码:

$orders = OrderProduct::where(function ($query) use ($request) {

})->with('order_products')->orderBy('status', 'desc')->paginate(50)->toArray();

order_products函数是:

 public function order_products()
    {
        return $this->hasMany("App\Order", "order_id", "order_id");
    }

它给我输出结果:

{
        "user_id": "1",
        "created_at": "2016-12-18 14:06:11",
        "status": "2",
        "note": "34535345",
        "order_id": "2",
        "address": "Kiev",
        "courier_id": null,
        "payment_type": "0",
        "order_products": [
          {
            "id": 73,
            "product_id": "1265",
            "amount": "1"
          },
          {
            "id": 74,
            "product_id": "1266",
            "amount": "1"
          }
        ]

我需要加入 order_productsproducts_details,以便为每个订单提供产品标题,例如:

"order_products": [
              {
                "id": 73,
                "product_id": "1265",
                "amount": "1",
                "title": "Product name"
              },
              {
                "id": 74,
                "product_id": "1266",
                "amount": "1",
                "title": "Product name"
              }
            ]

相反,我得到了一个新的模型输出作为响应:

"products_details": [
  {}, {}
]

如何加入两个 with 模型?

无需加入,只需使用您的第一个代码:

order_products 中,覆盖 toArray() 方法。

function toArray() {
  return [
    id         => $this->id,
    product_id => $this->product_id,
    amount     => $this->amount,
    title      => $this->details->name
  ];
}

至于$this->details->nameorder_productsproducts_details

之间的关系