【问题标题】:Design a specific situation in laravel ( many to many relationship)在 laravel 中设计一个特定的情况(多对多关系)
【发布时间】:2020-02-19 12:47:24
【问题描述】:

我想问一个具体的情况..

我有 3 个模型:

商店

价格

产品

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

例如:

如果我有价格为 100 美元的产品 A,我想将其设置为商店 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');

    }

}

价格.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】:

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

    return $this->belongsToMany(Store::class, 'store_prices')->witPivot('product_id');
    

    关于分组,您可以将 if 作为连接三个表(store、pice 和 pivot)的普通查询,然后根据 product_id 对结果进行分组

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-18
      • 2013-05-27
      • 1970-01-01
      • 2015-02-14
      • 2021-12-27
      • 2018-06-15
      • 1970-01-01
      • 2014-08-21
      相关资源
      最近更新 更多