dougan4663 2014-04-27 17:45 采纳率: 0%
浏览 31

重用模型中的对象

Currently I have a Ticket model.

I have these custom methods in this model:

public static function listing()
{
    $query = self::with('user', 'group', 'category', 'replies', 'club.country', 'club.membership.package', 'club.product');

    return $query->orderBy('updated_at', 'DESC')->paginate(20);
}

public static function total()
{
    return self::query()->count();
}

public static function open()
{
    return self::query()->where('status', '!=', 2)->count();
}

public static function search($search)
{
    $query = self::with('user', 'group', 'category', 'replies', 'club.country', 'club.membership.package', 'club.product');

    $query->where('subject', 'LIKE', '%'. $search .'%');

    return $query->orderBy('updated_at', 'DESC')->paginate(10);
}

When I use at the same time listing() or search() + total() and open() I believe it will be returned 3 objects.

So I wonder is it possible to inject/made availabe everywhere in the model the object returned by self::query()?

Now instead of calling/invoking self::query() or self::with() within all these custom methods I could instead refer to an existing object.

  • 写回答

1条回答 默认 最新

  • drodsh7940 2014-04-27 18:20
    关注

    What your asking for seems to be scopes.

    <?php
    class Model extends Eloquent {
        public function scopeTotal($query) {
            return $query->count();
        }
    
        public function scopeOpen($query) {
            return $query->where('status', 1);
        }
    }
    

    And then use it like Model::open()->get() to get all rows with status set to 1, or Model::open()->total() to count number of rows where status equals to 1 .

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看