我在查詢中使用 whereRelation 但沒有參考我想要的欄位有點奇怪
我的表結構是這樣的
訂單表:
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->string('shipment_id');
$table->integer('qty');
$table->string('item_code');
$table->timestamps();
});
出貨表:
Schema::create('shipments', function (Blueprint $table) {
$table->id();
$table->string('shipment_id')->unique(); // this reffering the ID from shipping lines
$table->string('delivery_plan');
$table->string('eta');
$table->string('destination');
$table->timestamps();
});
關系
/**
* Get the order associated with its shipments.
*/
public function shipments()
{
return $this->hasMany(Shipment::class);
}
/**
* Get the shipment associated with its order.
*/
public function order()
{
return $this->belongsTo(order::class);
}
我的查詢:
$orders = Order::whereRelation('shipments', function($query) {
$query->whereIn('destination', ['USA', 'CANADA']);
})
->leftJoin('shipments', 'orders.shipment_id', '=', 'shipments.shipment_id')
->addselect(DB::raw('SUM((qty)) as total_qty'))
->groupBy('orders.sales_id')
->groupBy('orders.item_code');
來自關系的查詢結果:
where exists (select * from `shipments` where `orders`.`shipment_id` = `shipments`.`id`)
我想要的查詢結果:
where exists (select * from `shipments` where `orders`.`shipment_id` = `shipments`.`shipment_id`)
它指的是shipping.id而不是shipping.shipment_id我該如何解決這個問題?
uj5u.com熱心網友回復:
在 laravel 中,默認primary key為modelis ID,您需要在 Eloquent model , Primary Keys中添加以下代碼
protected $primaryKey = 'your_pk';
如果您的關系不使用IDas key,則需要添加關系parameter功能 Eloquent 、Relationships
public function shipments()
{
return $this->hasMany(Shipment::class, 'foreign_key', 'local_key');
}
public function order()
{
return $this->belongsTo(order::class, 'foreign_key', 'owner_key');
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/426311.html
