微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法访问关系方法中的父枢轴属性

如何解决无法访问关系方法中的父枢轴属性

有 3 个模型:订单、产品和价格

每个订单有许多产品,每个产品都有一个价格,这取决于订单price_group_id 字段。

class Order extends Model
{
    public function products() {
        return $this->belongsToMany(Product::class)->withPivot(['quantity']);
    }
}

class Product extends Model
{
    public function price() {
        return $this->hasOne(Price::class)->where('price_group_id','=',$this->pivot->pivotParent->price_group_id);
    }
}

Price 模型具有 id、product_id、price_group_idvalue 字段。

我使用 $this->pivot->pivotParentProduct 模型中检索 Orderprice_group_id 属性它在 Laravel 中运行良好,但不适用于 Lighthouse 查询“试图获取非对象的属性 'pivotParent'”。似乎根本没有pivot和pivotParent。

有没有办法获得父枢轴属性或其他一些方法来实现这种关系?

GraphQL 架构的一部分:

type Query {
    orders: [Order!]! @all
    order(id: ID! @eq): Order @find
}

type Order {
    id: ID!
    price_group_id: ID!
}

type Product {
    id: ID!
    price: Price @hasOne
}

type Price {
    id: ID!
    value: Float!
    price_group_id: ID!
}

解决方法

我尝试了一些方法来解决这个问题,包括访问器而不是关系方法。 pivotParent 返回null,但我可以访问pivot!所以我可以通过这种方式获得 price_group_id 和相对价格:

public function getPriceAttribute() {
    return $this->hasOne(Price::class)->where('price_group_id',Order::find($this->pivot->order_id)->price_group_id)->first()->value;
}

产品架构:

type Product {
    id: ID!
    price: Float
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。