提问者:小点点

relate与pivot数据相等时只有一个关系


我在产品模型中有这种关系。每种产品都有很多价格,每个价格都可能有折扣:

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);

}]);

现在我想得到$product-

{
    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
}
}

折扣-


共1个答案

匿名用户

尝试在关系中添加透视表名称

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);

}]);