如何将where()用于属于with()的列

时间:2019-02-18 06:33:08

标签: laravel

我正在使用Laravel框架。 我想获取特定类别的促销数据。

X_train = mapper.fit_transform(X_train)
X_test = mapper.transform(X_test) # change fit_transform to transform

错误:

  

SQLSTATE [42S22]:找不到列:1054“ where子句”中的未知列“ category.id”(SQL:从<b>Table</b><br> product<br> ------<br> id<br> name<br> price<br> promotion<br> ----------<br> id<br> product_id<br> discount<br> category<br> ---------<br> id<br> name<br> product_category<br> ----------------<br> product_id<br> category_id<br> $promotions = Promotion::with('product')->with('category') ->whereIn('category_id', ['1','2']) ->paginate(9); Promotion model - connect relation for product and category // relationship with product public function product() { return $this->belongsTo('App\Model\Product'); } //relationship with category public function category() { return $this->belongsToMany('App\Model\Category', 'products_categories', 'product_id', 'category_id'); } 的{​​{1}}中选择count(*)作为集合。{{ 1}}在(1,2))

3 个答案:

答案 0 :(得分:2)

尝试

$promotions = Promotion::with('product.category') 
    ->whereIn('category_id', ['1','2'])
    ->paginate(9);

假设您必须在relations中创建正确的models

编辑:

促销模型中:

// relationship with product 
public function product()
{
    return $this->belongsTo('App\Model\Product');
}

产品型号:

//relationship with category
public function product_category() 
{
   return $this->belongsTo('App\Model\ProductCategory', 'product_id', 'id');
}

类别模型中:

//relationship with category
public function product_category() 
{
   return $this->belongsToMany('App\Model\ProductCategory', 'category_id', 'id');
}

查询类似:

$promotions = Promotion::with('product.product_category') 
    ->whereIn('category_id', ['1','2'])
    ->paginate(9)

答案 1 :(得分:1)

怎么样:

$promotions = Promotion::with([ 'product.category' => function($q){
    return $->whereIn('category_id', ['1','2']);
}]) 
->paginate(9);

如果您想获得所有ID为1,2的类别的促销,则可以执行以下操作:

$promotions = Promotion::whereHas('product.category' => function($q){
    return $->whereIn('category_id', ['1','2']);
}) 
->paginate(9);

这只会为您带来促销,而不是类别。如果那是您想要的。

答案 2 :(得分:1)

您可以简单地使用它:

$promotions = Promotion::whereHas(
            'product.category',
            function ($q) {
                $q->whereIn('category_id', ['1', '2']);
            })
            ->paginate(9);