laravel增删查改实例

来源:互联网 发布:软件培训班要多少钱 编辑:程序博客网 时间:2024/06/06 16:36
1.查
1)SalonQuestion::query()->orderBy('created_at', 'desc')->paginate(config('website.admin.page_size'));
2) SalonQuestion::find($id);
2.插入
SalonQuestion::insert([
            'salon_id' => $data['salon_id'],
            'title' => $data['title'],
            'description' => $data['description'],
            'answers_user_name' => $data['answers_user_name'],
            'answers_content' => $data['answers_content'],
            'amount' => setAmount(intval($data['amount'])),
            'status' => $data['status'],
            'created_at' => \Carbon\Carbon::now()
        ]);
注:批量插入时,将参数数组替换成多维数组即可
3.改
        $salon = SalonQuestion::find($id);
        if (!$salon) {
            return $this->error(route('admin.salonq.index'), '不存在,请核实');
        }
        $this->validate($request, $this->validateRules, $messages);
        $salon->salon_id = $request->input('salon_id');
        $salon->title = $request->input('title');
        $salon->description = $request->input('description');
        $salon->answers_user_name = $request->input('answers_user_name');
        $salon->answers_content = $request->input('answers_content');
        $salon->amount = setAmount(intval($request->input('amount')));
        $salon->status = $request->input('status');
        $salon->save();
        /**
        /*另一个更新方法
        */
        SalonQuestion::where('id','=';$id)->update(['salon_name'=>$salon_name])

4.删除
1)硬删
            $infos = SalonQuestion::find($id);
            if ($infos) {
                SalonQuestion::destroy($id);
            }
2)软删
use SoftDeletes;
数据库中要一个deleted_at
在迁移类中还要修改
5.关联两个表
在一个表的model中加一个方法类似如:   
 public function salon()
    {
        return $this->hasOne('App\Models\Salon','id','salon_id');
    }
SalonQuestion->Salon->salon_id;
6.查看一个sql的原语句
//对查询字段有要求的
WechatUser::select(DB::raw('DATE_FORMAT(created_at,\'%Y-%m-%d\') dates,count(*) as cunt'))
                ->where('created_at', '>', $labelTimes[0])
                ->where('created_at', '<', $labelTimes[7])
                ->groupBy('dates')->toSql();
7.laravel中获取刚刚插入的数据id
a.DB::insertGetId
b.save()方式插入 直接对象->id 就是新增id
8.laravel中连接查询实例
        /* 网站分类查询 */
        if (isset($filter['sort']) && $filter['sort']) {
                //这里的$filter用use关键字加上形式引入到内嵌方法的作用域中,这里将$filter定义为一个超全局变量也可以直接在内嵌方法作用域中使用
            $id = Relation::query()->join('categories', function($join) use ($filter){
                        $join->on('relations.belong_id', '=', 'categories.cate_id')->where('categories.cate_name', 'like', '%' . $filter['sort'] . '%');
                    })->get();
            foreach ($id as $v) {
                $web_id[] = $v->type_id;
            }
            $query->whereIn('web_id', $web_id);
        }

0 0
原创粉丝点击