[英]Relationship between many-to-many table and other one-to-many table
大家早上好
首先,要说我使用的是Laravel,因此是Eloquent ORM,但是我认为(更多)是纯粹的关系数据库问题,所以这就是为什么我在这里提到它。
有一阵子,我在many-to-many
表和many-to-many
表之间建立了联系。
有以下4个涉及的表:
特别是给定机器和产品,有N个限制。
到目前为止,我认为一切都很好,但是当我想将其转换为Laravel模型时,人们开始怀疑。
原则上,我们将具有以下三个模型:
通常,不需要建立many-to-many
模型,因为可以通过两个主要模型之一来访问它们。 在这种情况下,我们可以从Machine
或Product
访问数据透视表machine_products
。
问题来自于我要通过Eloquent访问的Machine
或Product
实例的restrictions
。 以同样的方式,我不知道如何通过restrictions
实例访问Machine
或Product
。
尽管现在只能解决第一个问题,但我现在选择的是一个选项。
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
表: id
, machine_id
, product_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.