【问题标题】:hasManyThrough not workinghasManyThrough 不工作
【发布时间】:2016-12-28 05:28:51
【问题描述】:

我有这张桌子,

categories: id | name | slug
Products: id | name | slug | category_id | brand_id
Brands: id | name | slug |

当我尝试将品牌带入功能类别时出现问题。

类别模型

public function brands()
{
   return $this->hasManyThrough('App\Brand', 'App\Product' 'brand_id', 'id');
}

品牌要么没有出现,要么显示在错误的类别中。

还有其他方法可以通过 Brands 产品吗?

【问题讨论】:

    标签: php sql laravel


    【解决方案1】:

    如下改变你的关系:

    public function brands()
    {
       return $this->hasManyThrough('App\Brand', 'App\Product' 'category_id','id','brand_id');
    }
    

    但是,我怀疑你可以使用hasManyThrough() 来检索这种关系。
    正如laravel site 所给出的,您的表格应该具有以下关系。

    Category 1-* Product 1-* Brand
    在你的情况下这是不可能的。

    我认为您必须使用以下方法手动完成:

    public function Brands($category_id){
        $products = Category::find($category_id)->Products()->get()->pluck('brand_id');
        $brands = Brands::whereIn('id','=',$products)->get();
        return $brands;
    }
    

    【讨论】:

      【解决方案2】:

      这是属于ToManyRelation

      类别模型

          public function brands()
          {
              return $this->belongsToMany('App\Brands', 'products', 'category_id', 'brand_id');
          }
      

      【讨论】:

        猜你喜欢
        • 2018-07-22
        • 2014-05-12
        • 2018-03-26
        • 1970-01-01
        • 2016-09-03
        • 1970-01-01
        • 2018-09-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多