摘抄自github的Laravel封装的模型基类

<?php
namespace App\Models;
trait Base
{
    /**
     * Store a new record.
     *
     * @param  $input
     * @return User
     */
    public function store($input)
    {
        return $this->save($this->model, $input);
    }
    /**
     * Save the input's data.
     *
     * @param  $model
     * @param  $input
     * @return mixed
     */
    public function save($model, $input)
    {
        $model->fill($input);
        $model->save();
        return $model;
    }
    /**
     * Get one record without draft scope
     *
     * @param $id
     * @return mixed
     */
    public function getById($id)
    {
        return $this->model->findOrFail($id);
    }
    /**
     * Delete the draft article.
     *
     * @param int $id
     * @return boolean
     */
    public function destroy($id)
    {
        return $this->getById($id)->delete();
    }
    /**
     * @param $field
     * @return mixed
     */
    public function getAllData($field = "*", $needToArray = true)
    {
        if ($needToArray) {
            return $this->model->select($field)->get()->toArray();
        } else {
            return $this->model->select($field)->get();
        }
    }
    /**
     * To judge the record is existence in you table
     *
     * @param $where
     */
    public function getFirstRecordByWhere($where)
    {
        return $this->model->where($where)->first();
    }
    /**
     * @param $id
     * @param $input
     * @return mixed
     */
    public function update($id, $input)
    {
        $this->model = $this->getById($id);
        return $this->save($this->model, $input);
    }
    /**
     * return  paginate list
     *
     * @param int $pagesize
     * @param string $sort
     * @param string $sortColumn
     * @return mixed
     */
    public function page($where = false, $pagesize = 20, $sortColumn = 'weight', $sort = 'asc')
    {
        if ($where) {
            if($sortColumn != 'created_at'){
                return $this->model->where($where)->orderBy($sortColumn, $sort)->orderBy('created_at', 'desc')->paginate($pagesize);
            }
            return $this->model->where($where)->orderBy($sortColumn, $sort)->paginate($pagesize);
        } else {
            return $this->model->orderBy($sortColumn, $sort)->paginate($pagesize);
        }
    }
    public function getThisModel()
    {
        return $this->model;
    }
    /**
     * Get all the records
     *
     * @return array User
     */
    public function all()
    {
        return $this->model->get();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值