如何通过外键在Laravel中查询Order_table关联的Invoice_table数据?
嘿,我来帮你搞定Laravel里这两个关联表的查询!首先得先把模型之间的关联关系定义好,这是Eloquent查询的基础,毕竟Laravel的ORM就是靠关联来简化操作的~
第一步:定义模型与关联关系
假设你的表名是order_table和invoice_table,我们先创建对应的模型并设置关联:
Order模型(app/Models/Order.php)
因为order_id是Invoice表的外键,所以一个订单可以对应多张发票,用hasMany关联:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; class Order extends Model { // 如果你的表名不是Laravel默认的复数形式,手动指定表名 protected $table = 'order_table'; // 如果order_id是该表的主键,需要指定(默认是id) protected $primaryKey = 'order_id'; // 定义与Invoice的关联 public function invoices(): HasMany { // 参数:关联模型、外键字段、当前模型的关联字段 return $this->hasMany(Invoice::class, 'order_id', 'order_id'); } }
Invoice模型(app/Models/Invoice.php)
每张发票属于一个订单,用belongsTo关联:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class Invoice extends Model { protected $table = 'invoice_table'; // 如果发票表主键不是id,也要指定 // protected $primaryKey = 'invoice_id'; // 定义与Order的关联 public function order(): BelongsTo { return $this->belongsTo(Order::class, 'order_id', 'order_id'); } }
第二步:常用查询场景示例
定义好关联后,就可以用各种简洁的方式查询数据了:
查询单个订单及其所有发票
推荐用with预加载避免N+1查询问题:// 获取ID为1的订单及其所有发票 $order = Order::with('invoices')->find(1); // 直接访问发票集合 $invoices = $order->invoices;查询单个发票及其所属订单
// 获取ID为1的发票及其对应的订单 $invoice = Invoice::with('order')->find(1); $order = $invoice->order;筛选出有发票的订单
过滤掉没有关联发票的订单:$ordersWithInvoices = Order::has('invoices')->get(); // 进阶:筛选出至少有2张发票的订单 $ordersWithMultipleInvoices = Order::has('invoices', '>=', 2)->get();根据发票条件筛选订单
比如查询所有关联发票金额大于100的订单:$orders = Order::whereHas('invoices', function ($query) { $query->where('amount', '>', 100); // 假设发票表有amount字段 })->get();关联查询时只获取指定字段
避免查询不必要的字段,提升性能:$orders = Order::with(['invoices' => function ($query) { // 只获取发票的ID、关联订单ID和金额 $query->select('invoice_id', 'order_id', 'amount'); }])->select('order_id', 'order_number')->get(); // 只获取订单的ID和编号原生Join风格查询
如果你更习惯用SQL的Join写法,也可以直接用DB门面:$results = DB::table('order_table') ->join('invoice_table', 'order_table.order_id', '=', 'invoice_table.order_id') ->select('order_table.*', 'invoice_table.invoice_id', 'invoice_table.amount') ->get();
最后提醒下:如果你的模型主键不是默认的id,一定要在模型里通过$primaryKey指定,否则关联会出错哦~
内容的提问来源于stack exchange,提问作者Probir
相关产品推荐
相关产品推荐

