【发布时间】:2020-12-22 14:41:32
【问题描述】:
我正在尝试过滤具有一对多关系的模型上的查询,但它不起作用。正确的输出应该删除所有过期的库存,但它会返回所有可用的库存。
产品: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);
}
}
【问题讨论】:
-
我认为你不需要在 Laravel 中格式化
Carbon对象。只需使用Carbon::now() -
@Daan 哦,好吧,不知道,谢谢!但这并不能解决我的问题。
标签: php mysql database laravel