从两个表中选择并在laravel中显示所有内容

时间:2016-07-01 11:07:22

标签: php mysql laravel-4.2

我想在两个表格中显示页面数据,但条件有点差,我无法弄清楚如何在Laravel 4中制作它。

所以我有表categories和表products。目前我在页面上显示所有类别,没有问题。问题是现在会有没有类别的产品,我想在页面上循环它们。

当admin创建产品时,他会选择类别,但如果不选择任何类别,则会在数据库1products中保存single_product默认值。

这是产品型号

public function categories()
{
    return $this->hasMany('Categories', 'category_id');
}

和类别模型

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');
}

这是视图

    <div class="col-xs-8 text-left" style="margin-top: 9px">
        @if($category['no_category'] == 0)
            Price: <strong>{{ $category->products()->min('price') }} $</strong>                         
        @else
            Price from: <strong>{{ $category->products()->min('price') }} $</strong> 
         @endif
    </div>

如何从single表中选择products列并在页面上显示它们以及类别名称?

1 个答案:

答案 0 :(得分:1)

然后没有类别。避免使用类别类,只需从产品类中直接获取。创建一个像:

这样的函数
public function singleItems()
{
   return $this->where("single_product", 1)->get();

}

然后你预先得出结果。请查看此信息以获取更多信息:

https://laravel.com/docs/5.1/eloquent-collections

我知道上面是另一个版本的laravel比你的,但我认为它应该工作。别告诉我,然后我会进一步了解。

相关问题