大家早上好
首先,要说我使用 Laravel,因此,Eloquent ORM,但我认为它更像是一个纯粹的关系数据库问题(或不是),所以这就是我在这里提到它的原因。
有一段时间,我做了一个多对多
表和一对多表的关系。
涉及的表有这4个:
- “机器”(id、名称、...)
- “产品”(id、名称、...)
- 'machine_products'(id、machine_id、product_id、价格)。
- “限制”(id、machine_product_id、day、begin_hour、end_hour)
特别是给定一台机器和一个产品,有 N 个限制。
到目前为止,我认为一切都很好,但是当我想将其转换为 Laravel 模型时,疑虑开始了。
原则上,我们会有以下三种模型:
- 机器
- 产品
- 限制
- (MachineProduct???理论上不需要)
通常,不需要创建多对多
模型,因为可以通过两个主要模型之一访问它们。在这种情况下,我们可以从 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?]->限制
。
我也希望能够做到这一点: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();
关于mysql - 多对多表与其他一对多表的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52831758/