douzi1991 2017-10-23 16:23
浏览 47
已采纳

如何从Laravel 5.5中的3个表中获取所需的行

I have 3 tables, Order, Products, Order_Products. I need get all field from order and products, thats ok using hasManyThrough(). But i need 1 more field from Order_products. How can i get this field ?

public function products()
{
   //in order model
 return $this->hasManyThrough('App\Models\Product','App\Models\OrderProduct','order_id','id','id','product_id');
}

using sql i need query like

SELECT products.*, order_products.order_id, order_products.count as order_count FROM products INNER JOIN order_products ON order_products.product_id = products.id WHERE order_products.order_id = 2

  • 写回答

1条回答 默认 最新

  • douchu4048 2017-10-23 16:41
    关注

    You can access intermediate table fields by using pivot attribute on model.

    Lets say you have product, Then you can access count field of orders_products

    $product->pivot->count;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?