我有一个产品表,其中一个产品类别,一个产品链接到多个类别。所有使用正确的外键将它们链接在一起。当用户属于某个类别时,使用ProductToCategory
模型选择此类别中的产品。在Laravel 5.1中使用链接数据库表的OrderBy
但我想要的是找到一个简单的方法,没有循环链接产品的输出到这个类别按名称排序产品。
我的数据库布局:
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
在我的产品分类模型我有:
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的多对多? – sleepless
ProductToCategory是一个产品可以链接到多个类别的表格。所以你有例如product_id 1在数据库中作为'product_id 1; category_id 1;''和'product_id 1; category_id 2;'。因此,我使用category_id执行查询以获取此类别中的所有产品。如果每个产品链接到一个类别 –