【问题标题】:Showing categories and lowest price with Laravel使用 Laravel 显示类别和最低价格
【发布时间】:2016-10-09 02:49:03
【问题描述】:

尝试显示数据库中的所有类别并根据类别中的产品显示最低价格。所以我到目前为止是: 型号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 视图的 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
    ]); 
}

【问题讨论】:

    标签: php mysql laravel laravel-4


    【解决方案1】:

    在您看来,您可能有一个foreach 声明。把它放在那里:

    $category->products()->min('price');

    这是该类别中最低的产品价格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多