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
            }
        ]
    }
阅读 9.1k
3 个回答
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;

应该是这样,我没验证。

可能有问题,找出他们之间的关系就好了

    //根据订单id查出订单详情
    public function getOrderDetail($oid)
    {
        return OrderDetail::where('order_id', $oid)->get();
    }
    
    //在订单详情 Model 写好关联关系
    public function productions()
    {
        return $this->belongsTo(Productions::class);
    }
    
    //视图
    @foreach($order_detail as $order)
        商品名:{{ $order->productions->name }}
    @endforeach

简单的方法就是关系表(订单详情)写一个model, 然后根据表的关系,看是用 hasOne() 还是hasMany(),找到关系即可,在Controller写db语句的时候直接with(’刚才的方法名‘)。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题