【问题标题】:Many-to-many relationship with additional foreign key与附加外键的多对多关系
【发布时间】:2020-05-01 05:27:17
【问题描述】:

我正在使用 Lumen 构建一个简单的食谱 API。

此时,设置是这样的:

  • 多对多关系:
    • recipe有很多ingredients
    • ingredient有很多recipes
  • 一对多关系:
    • recipe有很多steps

多对多关系是使用关联表实现的,ingredient_recipe

这按预期工作,并允许我访问,例如,$someRecipe->ingredients 以获取链接到特定食谱的所有成分。

但是 - 这是我不太确定的部分 - 给定特定的 recipe-ingredient 关系,ingredient 也有特定的 measure(例如“毫升”)和数量。

我现在解决这个问题的方法是简单地将measure_id 添加到关联表中的每个recipe-ingredient 关系:

我使用以下代码完成此操作:

$recipe->ingredients()->attach($ingredient_model, ['amount' => GIVEN_AMOUNT, 'measure_id' => GIVEN_MEASURE_ID);

这可行,但会使获取给定食谱中每种成分的数量和量度的查询稍微复杂一些。

我的问题:是否有另一种,也许更多Eloquent 方法来完成我没有看到的这个?或者对于我不知道的这些类型的案例,还有其他数据库设计最佳实践吗?

【问题讨论】:

  • 从数据库的角度来看,这是正确的解决方案。
  • 这是正确的。一个扩展是在成分上增加另一列,告诉您每种可用成分的数量(该量度)

标签: database laravel database-design eloquent lumen


【解决方案1】:

我有同样的问题,我的情况是:每个都有订单和产品,多对多,每个产品都有自己的计量单位和每个订单的数量,如下所示: pre-model of database

我不知道这是否正确,但我只是在产品模型中添加了一个方法

public function measurement()
{
    $measurement = Measurement::find($this->pivot->measurement_id);

    return $measurement;
}

现在我可以使用它了

@foreach ($order->products as $product)
    {{ $product->measurement()->name }}
@endforeach

我认为你只需要添加到成分模型中

public function measure()
{
    $measure = Measure::find($this->pivot->measure_id);

    return $measure;
}

【讨论】:

    【解决方案2】:
    // Recipe Model
    public function recipes()
        {
            return $this->belongsToMany('App\Recipe')->withTimestamps();
        }
    // Ingredient Model
     public function ingredients()
        {
            return $this->belongsToMany('App\Ingredient ')->withTimestamps();
        }
    
    // Controller 
    public function index()
        {
            $recipes= Recipe ::latest()->get();
            return view('admin.recipes.index',compact('recipes'));
        }
    
    // Blade file
    
     @foreach($recipesas $key=>$recipe)
    <tr>
    <td>{{$recipe->ingredients->name}}</td>
    </tr>
    @endforeach
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-25
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      相关资源
      最近更新 更多