尝试显示数据库中的所有类别和基于类别中的产品以显示最低价格。所以我到目前为止是:
模型 Categories.php
class Categories extends Eloquent {
protected $table = 'category';
protected $primaryKey = 'category_id';
public $timestamps = false;
public function products()
{
return $this->hasMany('Product', 'category_id');
//return $this->belongsToMany('Product', 'category_id');
}
}
这是Product.php
模型
class Product extends Eloquent {
protected $table = 'products';
protected $primaryKey = 'product_id';
public function categories()
{
return $this->hasMany('Categories', 'category_id');
//return $this->belongsToMany('Categories', 'category_id');
}
public $timestamps = false;
}
这是加载 index.blade.php View 的 HomeController.php
class HomeController extends BaseController {
public function index()
{
$products = Product::where('category_id', '!=', 1)
->with('category')
->min('price')
->get();
return View::make('site.index', [
'categories' => $categories
]);
}
}
现在当我加载页面时出现此错误
production.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to a member function get() on a non-object' in ....
这里有什么问题,如何显示类别和每个类别的最低价格?
更新:这是现在的样子
Categories.php 模型
class Categories extends Eloquent {
protected $table = 'category';
protected $primaryKey = 'category_id';
public $timestamps = false;
public function products()
{
return $this->hasMany('Product', 'category_id');
}
public function lowestProduct() {
return $this->products()->selectRaw('*, max(price) as aggregate')
->groupBy('products.product_id')->orderBy('aggregate');
}
}
HomeController.php
public function index()
{
$categories = Categories::with('lowestProduct')->get();
//$categories = Categories::paginate(15);
return View::make('site.index', [
'categories' => $categories
]);
}
最佳答案
在您看来,您可能有一个foreach
语句。把它放在那里:
$category->products()->min('价格');
这是该类别中最低的产品价格。
关于php - 使用 Laravel 显示类别和最低价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37709203/