设计laravel中的特定情况(多对多关系)

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

我想问一个具体情况。

我有3个型号:

商店

价格

产品

我必须为特定产品上的商店设置特定价格。

例如:

如果我的产品A的价格为100美元,我想将其设置为商店A为50美元,商店B为80美元...等

我所做的是我在商店和价格之间建立了很多关系

并且我将product_id存储在数据透视表中...

如下所示

Store.php

<?php

namespace App\Modules\Store\Models;
use App\Modules\Store\Models\Price;


class Store extends Model
{



    public function prices()
    {
        return $this->belongsToMany(Price::class,'store_prices');

    }

}

Price.php

<?php

namespace App\Modules\Store\Models;

use App\Modules\Store\Models\Store;
use Illuminate\Database\Eloquent\Model;

class Price extends Model
{
    protected $fillable = ['price'];

    public function stores()
    {
        return $this->belongsToMany(Store::class, 'store_prices');
    }

}


StorePrice.php

<?php

namespace App\Modules\Store\Models;

use App\Modules\Product\Models\Product;
use App\Modules\Store\Models\Price;
use App\Modules\Store\Models\Store;
use Illuminate\Database\Eloquent\Model;

class StorePrice extends Model
{
    protected $fillable = ['store_id', 'price_id', 'product_id'];
    protected $table = 'store_prices';

    public function store()
    {
        return $this->belongsTo(Store::class, 'store_id');
    }

    public function price()
    {
        return $this->belongsTo(Price::class, 'price_id');
    }

    public function product()
    {
        return $this->belongsTo(Product::class, 'product_id');
    }

}



在逻辑上是真的吗?

如果是,如何按产品分组价格并显示相关商店?

否则,我希望您能提出更好的建议

提前感谢

laravel eloquent laravel-5.7 laravel-query-builder
1个回答
0
投票

您不需要StorePrice模型。您只需要修改两个模型之一,然后像这样添加withPivot('product_id')

return $this->belongsToMany(Store::class, 'store_prices')->witPivot('product_id');
© www.soinside.com 2019 - 2024. All rights reserved.