Laravel Eloquent - Many to Many, Through, Where

10 浏览
0 Comments

Laravel Eloquent - Many to Many, Through, Where

我有三张表:产品,类别和产品_类别关系。

类别表有一个"type"字段,可以是"gender"或"garment"。所以一个产品有多个类别,一个类别也可以对应多个产品。

更加复杂的是,我有两种不同类型的类别(即性别和服装)。一个产品只能有一个"gender"类别和一个"garment"类别。

产品表:

---------------

| id | style |

---------------

| 1 | Style 1|

---------------

| 2 | Style 2|

---------------

类别表:

----------------------------

| id | type | name |

----------------------------

| 1 | gender | men's |

----------------------------

| 2 | gender | women's |

----------------------------

| 3 | garment | crew neck |

----------------------------

| 4 | garment | v neck |

----------------------------

| 5 | garment | tank top |

----------------------------

产品_类别关系表:

----------------------------

| product_id | category_id |

----------------------------

| 1 | 1 |

----------------------------

| 1 | 3 |

----------------------------

| 2 | 2 |

----------------------------

| 2 | 5 |

----------------------------

所以,根据上述数据,我们有:

Style 1是男士的圆领,Style 2是女士的背心。

我想以以下方式检索产品:

// 返回Style 1,男士,圆领

$product = Product::with(['gender', 'garment'])->find(1);

// 返回Style 2,女士,背心

$product = Product::with(['gender', 'garment'])->find(2);

我认为我可以在我的模型中设置一个标准的多对多关系,使用belongsToMany()方法将连接表设置为'product_has_category'。

在我的类别模型中,我有以下关系:

class Category extends Model

{

public function products()

{

return $this->belongsToMany('App\Product', 'product_has_category', 'category_id', 'product_id');

}

}

但是我不知道如何在产品模型中设置关系,以便按给定的类别类型获取类别。下面是我在产品模型中的代码,从某种程度上来说是有道理的,但是Laravel报错,说category.type是一个未知的列。

class Product extends Model

{

public function gender()

{

return $this->belongsToMany('App\Category', 'product_has_category', 'product_id', 'category_id')->where('type', '=', 'gender');

}

public function garment()

{

return $this->belongsToMany('App\Category', 'product_has_category', 'product_id', 'category_id')->where('type', '=', 'garment');

}

}

有人可以指点我如何设置这些数据关系吗?

0
0 Comments

在上述代码中,问题出现在`gender()`和`garment()`方法中的`where`条件上。当在关联模型的查询中链式调用查询方法(在这种情况下是`->where('category.type'...)`)时,需要移除`category.`部分,因为你已经在一个category查询上工作了。

解决方法是将`where`条件修改为如下形式:

public function gender()
{
    return $this->belongsToMany('App\Category', 'product_has_category', 'product_id', 'category_id')
        ->where('type', '=', 'gender'); // 移除 'category.'
}
public function garment()
{
    return $this->belongsToMany('App\Category', 'product_has_category', 'product_id', 'category_id')
        ->where('type', '=', 'garment'); // 移除 'category.'
}

现在,如果你调用`Product::with(['gender', 'garment'])->first()`,你将得到这两个分开的类别。

感谢devk的帮助!那真是个愚蠢的错误,不值得发帖。你解决得很好。非常感谢你的帮助!

0