【发布时间】:2017-04-02 10:11:34
【问题描述】:
我有一个包含产品的表格,一个包含类别,一个将产品链接到多个类别。所有这些都具有将它们链接在一起的正确外键。当用户在一个类别中时,使用ProductToCategory模型选择该类别中的产品。
但我想要找到一种简单的方法,而不是将链接产品的输出循环到该类别以按名称对产品进行排序。
我的数据库布局:
products
id: 1; name: testing 123
id: 2; name: testing 345
id: 3; name: testing 567
product_categories
id: 1; name: cat one
id: 2; name: cat two
id: 3; name: cat three
product_to_categories
id: 1; product_id: 1; product_category_id: 1
id: 2; product_id: 1; product_category_id: 2
id: 3; product_id: 2; product_category_id: 1
id: 4; product_id: 3; product_category_id: 1
id: 5; product_id: 3; product_category_id: 2
id: 6; product_id: 3; product_category_id: 3
在我的 ProductCategory 模型中,我有:
public function ProductToCategory() {
return $this->hasMany('App\Models\ProductToCategory');
}
在我的 ProductToCategory 模型中,我有:
public function Product() {
return $this->belongsTo('App\Models\Product', 'product_id');
}
在我的控制器中:
$linked_products = $category->ProductToCategory()->get();
foreach($linked_products as $linked_product) {
if($linked_product->Product->is_active == 1) {
$array[$linked_product->product_id] = $linked_product->Product);
}
}
这给了我$linked_product->Product 我需要的产品信息。
但是在模型中使用 Eloquent 方法,我想在给我查询结果之前按名称订购产品。
我该怎么做?
【问题讨论】:
-
什么是 ProductToCategory?为什么不将多对多与 belongsToMany 一起使用?
-
ProductToCategory 是一个表格,其中一个产品可以链接到多个类别。因此,例如 product_id 1 在数据库中为
product_id 1; category_id 1;和product_id 1; category_id 2;。因此,我使用 category_id 进行查询以获取该类别中的所有产品。如果每个产品都链接到一个类别会更简单
标签: php mysql laravel laravel-5