【问题标题】:How to Show colors related to products using laravel?如何使用 laravel 显示与产品相关的颜色?
【发布时间】:2020-01-23 18:06:29
【问题描述】:

我试图显示与产品相关的产品颜色我已经在数据库中创建了一个关系表我只想知道当我单击特定产品时将显示与该产品相关的颜色。谢谢

我遇到错误如何解决? https://flareapp.io/share/VmeXLq5Q#F56

有人有想法吗?

产品颜色模型

          class Product_color extends Model
          {
          public function products()
          {
          return $this->belongsToMany('App\Product', 'available_product_color', 'product_color_id', 
         'product_id');
          }
          }

产品型号

           class Product extends Model
           {
           public function sizes()
           {
           return $this->belongsToMany('App\Product_sizes', 'available_product_sizes', 'product_id', 
          'product_size_id');
            }

         public function color()
         {
         return $this->belongsToMany('App\Product_color', 'available_product_color', 'product_id', 
        'product_color_id');
         }

         }

控制器

       public function single_product($product_slug)
       {       
      $single_product = Product::with('sizes','color')->where('product_slug',$product_slug)->first();      
      return view('front_end/single_product',compact('single_product'));
       }   
       }

HTML 视图

                <div class="form-group product__option">
                <label class="product__option-label">Color</label>
                <div class="input-radio-color">
                <div class="input-radio-color__list">
                @foreach($single_product->color as $color)   
                <span><img src="{{$color->color_image}}"></span>
                @endforeach                                                    
                </div>
                </div>
                </div>

【问题讨论】:

  • 您的代码正在搜索名称为 product_colors 的表,请检查您是否有,如果您不确定如何使用,我建议您查看数据透视表命名约定的文档工作。

标签: laravel


【解决方案1】:

我强烈建议在命名类时使用驼峰式。它是一个非常好的约定和帮助。所以理想情况下Product_color 应该是ProductColor 或至少Product_Color。这也有助于 laravel 很容易地找到相关信息。根据 laravel 约定,您的数据透视表应按字母顺序命名,因此字母 CP 之前,应将其命名为 ColorProduct 否则在模型中指定表的名称

class Product_color extends Model
{
  protected $table = 'available_product_color ??';

  public function products()
  {
    return $this->belongsToMany(
         'App\Product', 
         'available_product_color',
         'product_color_id', 
         'product_id'
     );
   }
 }

这里是文档的链接。 https://laravel.com/docs/6.x/eloquent-relationships#many-to-many

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    相关资源
    最近更新 更多