繁体   English   中英

多对多表与其他一对多表之间的关系

[英]Relationship between many-to-many table and other one-to-many table

大家早上好

首先,要说我使用的是Laravel,因此是Eloquent ORM,但是我认为(更多)是纯粹的关系数据库问题,所以这就是为什么我在这里提到它。

有一阵子,我在many-to-many表和many-to-many表之间建立了联系。

有以下4个涉及的表:

  • '机器'(ID,名称,...)
  • '产品'(ID,名称,...)
  • “ machine_products”(id,machine_id,product_id,价格)。
  • “限制”(id,machine_product_id,日期,begin_hour,end_hour)

特别是给定机器和产品,有N个限制。

到目前为止,我认为一切都很好,但是当我想将其转换为Laravel模型时,人们开始怀疑。

原则上,我们将具有以下三个模型:

  • 产品
  • 限制
  • (MachineProduct ???在理论上没有必要)

通常,不需要建立many-to-many模型,因为可以通过两个主要模型之一来访问它们。 在这种情况下,我们可以从MachineProduct访问数据透视表machine_products

问题来自于我要通过Eloquent访问的MachineProduct实例的restrictions 以同样的方式,我不知道如何通过restrictions实例访问MachineProduct

尽管现在只能解决第一个问题,但我现在选择的是一个选项。

Restriction::find(Machine::find(1)->products()->first()->pivot->id);

我们可以建议一个更优雅,更实用的解决方案,以便从产品/机器中获得限制并向后退?

谢谢!

编辑

我想要这样的东西:

Machine::find(1)->products()->first()->restrictions或该Product::find(1)->machines()->first()->[pivot?]->restrictions

我还希望能够做到这一点: Restriction::find(1)->[pivot?]->machine (或产品)

这是三个模型:

class Machine extends Model
{
    public function products()
    {
        return $this->BelongsToMany('App\Product', 'machine_products')->withPivot('id','price');
   }
}


class Product extends Model
{  
    public function machines()
    {
        return $this->BelongsToMany('App\Machine', 'machine_products')->withPivot('price');
    }

}


class Restriction extends Model
{
    // Nothing
}

通常不建议(或不必要)在数据透视表中包含id列。

我将其删除并调整restrictions表: idmachine_idproduct_id ,...

这满足了您的第二个要求: Restriction::find(1)->machine

相反的方向仍然是一个问题。 我认为对此没有完美的解决方案:

Restriction::where('machine_id', $machine_id)
    ->where('product_id', $product_id)
    ->get();

您可以使用范围将其简化:

class Restriction extends Model {
    public function scopeByIds($query, $machine_id, $product_id) {
        $query->where('machine_id', $machine_id)
            ->where('product_id', $product_id);
    }
}

Restriction::byIds($machine_id, $product_id)->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM