2015-04-04 75 views
1

我想弄清楚Laravel中的某些东西。 我有一个模型'手机'和一个方法countproducts()。 每款手机都有很多'产品'。Laravel的查询方法

我使用countproducts()来计算手机所拥有的产品。

$phones=Phone::where(function($query){ 
    if(isset($min_weight) && isset($max_weight)){ 
     $query-> where('weight','>=',$min_weight); 
     $query-> where('weight','<=',$max_weight); 
    } 

这就是我现在查询手机的方式。

是否可以查询和显示只能说有超过50个产品的手机?

在此先感谢

编辑:Phone.php

<?php namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Phone extends Model { 

    public function productnum() 
    { 
     return $this->hasMany('App\Product'); 
    } 

    public function productStore() 
    { 
     return $this->hasOne('App\Store'); 
    } 

    public function category(){ 
     return $this->belongsTo('App\Category'); 
    } 

    public function minprice(){ 
     return $this->productnum->min('newprice'); 
    } 

    public function maxprice(){ 


     return $this->productnum->max('newprice'); 
     } 
    } 

Product.php

<?php namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Product extends Model { 

    public function manufacturer(){ 
     return $this->hasOne('manufacturer'); 
    } 

    public function phone(){ 
     return $this->belongsto('App\Phone'); 
    } 

    public function category(){ 
     return $this->belongsto('App\Category'); 
    } 
    public function store(){ 
     return $this->belongsto('App\Store'); 
    } 

回答

1

直起docs

$phones = Phone::has('products', '>=', 50)->get(); 

你应该能够get()where()条款之前放置。

+0

我收到错误'调用成员函数getRelationCountQuery()在一个非对象',当我做出改变; /我GOOGLE了它没有太多有关该错误的信息 – George 2015-04-04 11:47:24

+0

可能应该有'contrproducts'而不是'products'? – 2015-04-04 15:51:17

+0

感谢@AnatoliyArkhipov为了帮助我。 :)什么是控制?我的代码中没有类似的东西 – George 2015-04-04 16:27:25