我正在尝试过滤具有一对多关系的模型的查询,但它不起作用。正确的输出应该删除所有过期的股票,但它会返回所有可用的股票。
产品:hasMany(Stock::class)
库存:belongsTo(Product::class)
代码:
$keyword = $request->keyword;
$data = Product::with('stocks')
->where([
['pharmacy_id', '=', auth()->user()->pharmacy->id],
])
->where(function($productModel) use($keyword) {
$productModel->where('name', 'LIKE', "%$keyword%")->orWhere('sku', 'LIKE', "%$keyword%");
})
->whereHas('stocks', function($stockModel) {
$stockModel->where('expiry', '>', Carbon::now()->format('Y-m-d'));
})->get();
当前输出:
[
{
"id": 1,
"sku": "xpzidfa1454995",
"name": "Jaqueline Will",
"category": "medicine",
"type": "manufactured",
"selling_price": "1.00",
"pharmacy_id": 1,
"created_at": "2020-12-22T11:40:32.000000Z",
"updated_at": "2020-12-22T11:40:32.000000Z",
"stocks": [
{
"id": 3,
"product_id": 1,
"expiry": "2025-10-10",
"amount": 40,
"supplier_id": 1,
"pharmacy_id": 1,
"created_at": "2020-12-22T11:45:39.000000Z",
"updated_at": "2020-12-22T11:45:39.000000Z"
},
{
"id": 5,
"product_id": 1,
"expiry": "2020-10-10",
"amount": 40,
"supplier_id": 1,
"pharmacy_id": 1,
"created_at": "2020-12-22T11:45:39.000000Z",
"updated_at": "2020-12-22T11:45:39.000000Z"
}
]
}
]
正确输出:
[
{
"id": 1,
"sku": "xpzidfa1454995",
"name": "Jaqueline Will",
"category": "medicine",
"type": "manufactured",
"selling_price": "1.00",
"pharmacy_id": 1,
"created_at": "2020-12-22T11:40:32.000000Z",
"updated_at": "2020-12-22T11:40:32.000000Z",
"stocks": [
{
"id": 3,
"product_id": 1,
"expiry": "2025-10-10",
"amount": 40,
"supplier_id": 1,
"pharmacy_id": 1,
"created_at": "2020-12-22T11:45:39.000000Z",
"updated_at": "2020-12-22T11:45:39.000000Z"
}
]
}
]
库存型号:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Stock extends Model
{
use HasFactory;
protected $fillable = [
'product_id',
'expiry',
'amount',
'supplier_id',
'pharmacy_id',
];
public function pharmacy() {
return $this->belongsTo(Pharmacy::class);
}
public function product() {
return $this->belongsTo(Product::class);
}
}
最佳答案
要删除过期的库存记录,应对急切加载施加约束
$keyword = $request->keyword;
$data = Product::with(['stocks' => fn($query) => $query->whereDate('expiry', '>', now())])
->where([
['pharmacy_id', '=', auth()->user()->pharmacy->id],
])
->where(function($productModel) use($keyword) {
$productModel->where('name', 'LIKE', "%$keyword%")->orWhere('sku', 'LIKE', "%$keyword%");
})
->get();
关于php - Laravel 过滤一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65410666/