我没有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的类别。
解决它!
我将此添加到我的模型中
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句