0
votes

i have this relation in product model. each product has a many price and each price may be has a discount:

public function multiprices()
{
   $id = $this->id;
   // $id = 2597 (i need get product id to find discount)
    return $this->belongsToMany('App\Multiprice')->with(['discount' => function($query) use ($id) {
        $query->where('product_id', $id);

}]);

now i want to need get $product->id in this function. $this->id return null & the belongsTomany has a $product_id in pivot.

{
    id: 18,
    name: "",
    price: "850000",
    sort_order: 4,
    desc: "",
    slug: null,
    size_id: 5,
    cat_id: 4,
    material_id: 2,
    created_at: "2019-12-21T09:28:37.000000Z",
    updated_at: "2020-06-27T14:33:19.000000Z",
    kos: 1597,
pivot: {
    product_id: 1597,
    multiprice_id: 18
},
discount: {
    id: 648,
    name: "",
    desc: null,
    price: "130000",
    uses: 0,
    max_uses: 3,
    is_fixed: 0,
    active: 0,
    product_id: 1597,
    material_id: null,
    multiprice_id: 18,
    created_at: "یکشنبه 02 شهریور 1399 ساعت 19:15",
    updated_at: "2020-08-24T08:18:58.000000Z",
    delete: 1
}
}

the discoun->product_id is not the same of $this->pivot->product_id

1

1 Answers

0
votes

try with add pivot table name in relationship

public function multiprices()
{
   $id = $this->id;
   // $id = 2597 (i need get product id to find discount)
    return $this->belongsToMany('App\Multiprice','pviot_table_name')->with(['discount' => function($query) use ($id) {
        $query->where('product_id', $id);

}]);