dongqie2010 2015-09-01 01:04
浏览 42
已采纳

Laravel查询生成器链接

I want to define blocks of query builder within my model: So it's cunctions might be used like this:

class Transactions extends Eloquent {

public function dateRange($from,$to){
    return $this->whereBetween('date', [$from,$to]);
}

public function category($categ){
    return $this->where(['categ' => $categ]);
}
...etc , more query block functions
}

so I could chain ans reuse these, like so:

$t = new Transactions();
dd($t->category($cat)->dateRange()->get())

or as i desire ...

$t2 = new Transactions();
dd($t2->dateRange()->get()) 

This (first example of usage) will thow A Call to undefined method Illuminate\Database\Query\Builder::dateRange()

p.s. second example works, but i need to chain more than one of Qblocks to my model instance...

  • 写回答

1条回答 默认 最新

  • doucuo8618 2015-09-01 01:10
    关注

    Try to change your code like this:

    class Transactions extends Eloquent {
    
        public function scopeDateRange($query, $from, $to){
            return $query->whereBetween('date', [$from, $to]);
        }
    
        public function scopeCategory($query, $categ){
            return $query->where(['categ' => $categ]);
        }
    }
    

    You should take a look at the query scope documentation of Eloquent : http://laravel.com/docs/5.0/eloquent#query-scopes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部