[英]Laravel 5: sort products by categories,
我没有laravel的丰富经验,但是我正在尝试按类别对产品进行分类...我已经可以对所有产品进行分类,但不能按类别进行分类。
你们能帮我吗?
模型:
class Product extends Model {
protected $table = 'products';
public function getCategoriesListAttribute(){
return $this->categories()->lists('id');
}
public function categories(){
return $this->belongsToMany('App\Modules\Webshop\Models\ProductCategory', 'category_product', 'product_id', 'category_id')->withTimestamps();
}}
产品表:
Schema::create('products', function(Blueprint $table)
Schema::create('category_product', function(Blueprint $table)
Schema::create('product_categories', function(Blueprint $table)
Schema::create('product_tag', function(Blueprint $table)
控制器:
class ProductsController extends Controller {
public function __construct()
{
//$this->middleware('auth');
}
public function index()
{
$viewmodel = array(
"categories"=> ProductCategory::where('visible', '1')->get(),
"products" => Product::has('categories')->get(),
"page"=>Page::where('href','=', '/')->first(),
);
return view('Webshop::frontend.view.products.index', $viewmodel);
}
}
index()仅显示具有任何类别的产品。
如果你们需要更多信息,请随时询问:)
编辑:
我正在我的控制器中尝试此操作。
public function index()
{
$viewmodel = array(
"products" => Product::with('categories')->where('category_id','23'),
);
return view('Webshop::frontend.view.products.index', $viewmodel);
}
和这个:
$viewmodel = array(
"products" => Product::leftJoin('category_product', 'category_product.product_id', '=', 'products.id')
->leftJoin('product_categories', 'product_categories.id', '=', 'category_product.category_id')
->where('category_id', 23)
->first(['products.*']),
);
return view('Webshop::frontend.view.products.index', $viewmodel);
我有一个ID为23的类别。
好吧,如果您真的orderBy()
“排序”,请使用orderBy()
查询构建器方法。 如果需要按位于另一个表中的某些数据进行排序,请使用join()
将这些字段包括在查询中。 请注意,在Eloquent Builder中使用join()
时,还需要使用select("products.*")
否则Laravel会尝试将错误的列提取到查询结果中。
如果需要按类别对查询结果进行分组,请使用查询结果集合的group()
方法。 您可以按category_id
字段分组。
修复!
我将此添加到我的模型中
public function scopeGetCategorieSlug($query, $category_slug)
{
return $query->leftJoin('category_product', 'category_product.product_id', '=', 'products.id')
->leftJoin('product_categories', 'product_categories.id', '=', 'category_product.category_id')
->where('product_categories.slug', $category_slug)
->get(['products.*']);
}
这给我的控制器
public function show($category_slug)
{
$viewmodel = array(
"categories"=> ProductCategory::where('visible', '1')->get(),
"products" => Product::getCategorieSlug($category_slug),
"page"=>Page::where('href','=', '/')->first(),
);
return view('Webshop::frontend.view.products.index', $viewmodel);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.