2015-04-04 73 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