【问题标题】:Laravel displaying three tables with relationships, one table connects the two other tablesLaravel 显示三个有关系的表,一个表连接另外两个表
【发布时间】:2020-01-15 17:06:45
【问题描述】:

我有 3 张桌子;

 Sizes - columns: (id, height, width)
 Media - columns: (id, media, description)
 Price - columns: (id, size_id, media_id, price)

每个尺寸,在媒体表中都有每条记录,但价格由每个单独的尺寸和媒体决定。

我的目标是像这样显示每种尺寸和媒体及其价格;

8x10 - Media 1 - $20.00
8x10 - Media 2 - $24.00
8x10 - Media 3 - $30.00
8x12 - Media 1 - $24.00
8x12 - Media 2 - $28.00
8x12 - Media 3 - $32.00

到目前为止我尝试过的是(尺寸模型):

public function media() {
  return $this->hasManyThrough('\App\Size', '\App\Prices');
}

public function prices() {
  return $this->hasManyThrough('\App\Size', '\App\Prices');
}

不使用关系,我可以这样做;

$s = Size::all();
    foreach ($s as $size) {
        $m = Media::all();
        foreach ($m as $media) {
            $p = Price::where('enlarge_size_id', '=' , $size['id'])->where('enlarge_media_id', '=', $media['id'])->first();
            echo $size['height'] . 'x' . $size['width'] . ' -> ' . $media['media'] . ': $' . $p['price'] . '<br />';
        }
    }

这可能在 Laravel 中的关系中实现吗?我只是在寻找一种更简洁的方法来查看、更新和添加。

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

    在你的情况下,你应该使用多对多关系

    首先定义与媒体表具有多对多关系的 Size 模型:

    class Size extends Model
    {
        public function media() {
          return $this->belongsToMany(Media::class ,'Price', 'size_id', 'media_id')->withPivot('price');
        }
    
    }
    

    然后定义媒体模型以反转与尺寸表的关系:

    class Media extends Model
    {
        public function sizes() {
           return $this->belongsToMany(Size::class ,'Price', 'media_id', 'size_id')->withPivot('price');
        }
    
    }
    

    如果您想访问数据透视表中的价格列,您可以在相关模型中使用数据透视道具,例如:

       $sizes=Size:with('media')->first();
        foreach ($sizes->media as $media){
           $price=$media->pivot->price
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-23
      • 2015-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-10
      • 1970-01-01
      相关资源
      最近更新 更多