2016-11-18 110 views
0

我有一个产品表,其中一个产品类别,一个产品链接到多个类别。所有使用正确的外键将它们链接在一起。当用户属于某个类别时,使用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方法我想在给我查询结果之前按名称排序产品。

我该怎么做?

+0

什么是ProductToCategory?为什么不使用belongsToMany的多对多? – sleepless

+0

ProductToCategory是一个产品可以链接到多个类别的表格。所以你有例如product_id 1在数据库中作为'product_id 1; category_id 1;''和'product_id 1; category_id 2;'。因此,我使用category_id执行查询以获取此类别中的所有产品。如果每个产品链接到一个类别 –

回答

1

看来你有一个many-to-many relation。您不需要ProductToCategory-Model。

相反,你需要在你的产品分类,型号这种关系:

public function products() 
{ 
    return $this->belongsToMany('App\Models\Product'); 
} 

,一个在您的产品型号:

public function categories() 
{ 
    return $this->belongsToMany('App\Models\ProductCategory'); 
} 

您还可以指定枢轴表的名称( product_to_category-table)和列名称:

public function categories() 
{ 
    $this->belongsToMany('App\Models\ProductCategory', 'table_name', 'product_id ', 'product_category_id '); 
} 

使用此功能,您可以查询它s如下:

$linked_products = $category->products()->orderBy('name')->get(); 
+0

但会更加简单但注意​​到产品ID 1属于类别ID 1和类别ID 2? –

+0

@AlvinBakker看看我更新的答案。 Laravel根据你的模型名称猜测名字。但是,如果列或表的命名方式不同,则可以明确指定它们。 – sleepless

+0

我已经调整了数据库布局的问题,告诉你我为什么需要'product_to_categories'表,因为一个产品可以分为三类。您的适应性答案是,类别和产品链接在一起,只是命名不同。但事实并非如此,因为中间有一个。希望在我的问题中添加数据库布局使得这更清晰 –