Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

laravel - No access to parent pivot attributes in relationship method

There are 3 models: Order, Product and Price

Each Order has many Products, each Product has a Price which depends on the Order's price_group_id field.

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 model has id, product_id, price_group_id and value fields.

I retreive Order's price_group_id attribute in Product model with $this->pivot->pivotParent and it works fine in Laravel, but it doesn't work with Lighthouse queries: "Trying to get property 'pivotParent' of non-object". It seems like there is no pivot and pivotParent at all.

Is there any way to get a parent pivot attributes or maybe some other way to implement such relationships?

A part of GraphQL schema:

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!
}
question from:https://stackoverflow.com/questions/66064134/no-access-to-parent-pivot-attributes-in-relationship-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...