Laravel Eloquent关系过滤:仅返回fk_customer_id非空的已序列化项
在我的系统中,当一个产品售出时,fk_customer_id 列在 serializations 表中变为NOT NULL。如果产品仍有库存,fk_customer_id 仍然为NULL。在采购退货页面,只应允许对已售出的产品进行退货。
用户输入 serial_emei_number,系统应在 serializations 表中检查匹配的行。如果 fk_customer_id 为NULL,产品就不应可选用于退货。如果 fk_customer_id 为NOT NULL,产品应可选。
当前,我在 returnInvoice 函数中的查询仍然返回尚未销售的产品。
public function returnInvoice(Request $request, string $type){
switch ($type) {
case 'invoice_no':
return Receiving::with("serializeItems", "serializeItems.fk_receiving_id.fk_vendor_id")
->whereNotNull("fk_customer_id")
->whereLike(["invoice_no"], $request->q)
->WhereHasLike("fk_vendor_id", ["name", "primary_phone"], $request->q)
->WhereHasLike("serializeItems", ["serial_emei_number"], $request->q)
->leftJoin('vendors', 'receivings.fk_vendor_id', '=', 'vendors.id')
->selectRaw("receivings.*, CONCAT(invoice_no, ' : ', vendors.name, ' : ', vendors.primary_phone) as text")
->groupBy("$request->column")->withSum("invoiceItem", 'subtotal')->get()->take(10);
break;
default:
return serialization::with(["fk_receiving_id", "fk_receiving_id.fk_vendor_id", "fk_receiving_invoice_no"])
->whereLike(["serial_emei_number"], $request->q)
->leftJoin('receivings', 'serializations.fk_receiving_id', '=', 'receivings.id')
->leftJoin('vendors', 'receivings.fk_vendor_id', '=', 'vendors.id')
->selectRaw("serializations.*, CONCAT(serial_emei_number, ' : ', receivings.invoice_no, ' : ', vendors.name) as text")
->groupBy("$request->column")
->get()->take(10);
break;
}
}
解决方案
你需要在 serializations 表上也添加 ->whereNotNull("fk_customer_id") 条件。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。