php - 使用 Laravel 显示类别和最低价格

标签 php mysql laravel laravel-4

尝试显示数据库中的所有类别和基于类别中的产品以显示最低价格。所以我到目前为止是: 模型 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/

相关文章:

php - 将此字符串:“ab1_cd2_ef3.php”转换为3个变量:“ab1”,“cd2”和“ef3”?

php - 我应该在用户输入错误时抛出异常吗?

php - 在 ubuntu 上构建 php5.3.8,得到错误 : configure: error: Unable to locate gmp. h

php - 从 whereIn 获取重复项 - Laravel

php - Mac OS X El Capitan 需要 Mcrypt PHP 扩展

php - 拉拉维尔 4 : "Replace" Eloquent instead of "Select"

php - 使 PHP 计算器存储和显示历史记录

java - 从 JDBC 数据库中检索数据到 Jtable

php - 根据表单输入过滤数据库查询

php - 由 Taxonomy Meta 过滤的自定义 $wpdb 帖子