php - laravel多表关联查询问题

查看:137
本文介绍了php - laravel多表关联查询问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我有三张表:
1.order_invoices 订单表
2.order_invoice_productions 订单明细表
3.productions 商品表

字段说明:

order_invoice 订单表

  • id 主键id

  • order_sn 订单号

  • money 订单金额

  • ...



order_invoice_productions 订单明细

  • id 主键ID

  • invoice_id 关联订单表中id

  • production_id 商品id,关联商品表id

  • ....

productions 商品表

  • id 商品id

  • cate 商品分类

  • title 商品名称

  • price 商品价格

  • ...

问题:
1.订单详情,由订单id获得订单的详情,订单与订单明细信息,同时包含商品的名称,分类等等商品属性
2.订单列表,同样包含订单,订单明细,商品属性的信息

这样的查询该怎么写,在order_invoice模型中hasmany了order_invoice_productions;

请各位大大解答一下...谢谢!

修改

OrderInvoices::where('id',$invoice_id)->with(['orderInvoiceProductions'=>function($query){
            $query->with(['production'=>function($query){
                $query->select('title','category_alias');
            }]);//->select('id','production_id','discounted_price','discount_id','cop_reward')->get();
    }])->get();

返回值:

{
        "id": 1,
        "order_sn": "XT2017071908070144062",
        "total_price": "4800.00",
        "deleted_at": null,
        "created_at": "2017-07-19 08:01:45",
        "updated_at": "2017-07-19 09:51:13",
        "order_invoice_productions": [
            {
                "id": 9,
                "order_invoice_id": 1,
                "order_sn": "XT2017071908070144062",
                "production_id": 1,
                "deleted_at": null,
                "created_at": "2017-07-19 09:35:49",
                "updated_at": "2017-07-19 09:51:13",
                "production": null
            },
            {
                "id": 10,
                "order_invoice_id": 1,
                "production_id": 2,
                "deleted_at": null,
                "created_at": "2017-07-19 09:35:49",
                "updated_at": "2017-07-19 09:51:13",
                "production": null
            }
        ]
    }

解决方案

class Invoice extends Model
{
    public function invoiceProduction()
    {
        return $this->hasOne(InvoiceProduction::class, 'invoice_id', 'id');
    }
}

class InvoiceProduction extends Model
{
    public function production()
    {
        return $this->hasOne(Production::class, 'production_id', 'id');
    }
}

class Production extends Model
{

}

$invoice = Invoice::with(['invoiceProduction' => function ($query) {
    $query->with('production');
}])->get();

$invoice[0]->invoiceProduction->production;

应该是这样,我没验证。

这篇关于php - laravel多表关联查询问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆