php - Laravel 过滤一对多关系

标签 php mysql database laravel

我正在尝试过滤具有一对多关系的模型的查询,但它不起作用。正确的输出应该删除所有过期的股票,但它会返回所有可用的股票。

产品: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/

相关文章:

mysql - R Shiny 应用程序中的 SQL 查询语法 - CAST

mysql - 左连接出现 "unknown column"错误

mysql - 如何在现有的 mysql 表中进行按月分区?

mysql - 读取 row = mysql_fetch_row(result) 返回的 mySQL 数据库的行集,这是一个字符串数组,用于从中提取各个字段

php - 在 session 中保存常量 GET 变量

php - 在 PHPSpec stub 上仅模拟一种方法

python - django MySQLdb 不同步

database - 从 Linux shell 与 .db 文件交互

php - MySQL - 在插入时返回生成的 AUTO_INCREMENT 值

PhpStorm 2016.3.3 找不到带有 PHPUnit 6.0 的测试类。*