Laravel 与聚合的关系

问题描述 投票:0回答:1

我正在尝试通过嵌套关系的自定义列来订购相关模型

我有这些型号

产品

productDefaultSpecs
,这是一个
hasMany(ProductDefaultSpec::class)
关系

ProductDefaultSpec

productSpecType
,这是一个
belongsTo(ProductSpecType::class)
关系

产品规格类型 有一个

order_value
(int) 字段

我通过这种关系实现了一些预期的行为

public function productDefaultSpecs()
{
    return $this->hasMany(ProductSpec::class)
        ->withAggregate('productSpecType', 'order_value')
        ->orderBy('product_spec_type_order_value', 'DESC');
}

当我从数据库检索产品时,ProductDefaultSpec 按预期排序。

但是当我尝试使用例如

$product->productDefaultSpecs()->delete()
我收到 SQL 错误

SQLSTATE[42S22]:未找到列:1054“order 子句”中的未知列“product_spec_type_order_value”

错在哪里?或者有没有更好的方法来获取定制订购的相关模型?

laravel relation
1个回答
0
投票

在 Laravel 中,使用 withAggregate 时,无法应用 orderBy 子句。我尝试使用 withAggregate 检索最新的相关数据,但它返回了第一个数据,因为它忽略了 orderBy 或latest() 的影响。

© www.soinside.com 2019 - 2024. All rights reserved.