laravel -ORM 数据库

周楷
2023-12-01

不为空

DB::table('user')->where('img','!=','')->get();

或:

DB::table('user')->whereNotNull('img')->get();

Laravel Eloquent ORM字段及时间处理

laravelORM hide 和fillable ,appends属性

Db::Raw

select sum()

public function history_sum()
{
    return $this->hasOne(InstagramActionsHistory::class, 'account_id')
        ->select('account_id',
            DB::raw('sum(case when action_type = 1 then 0 END) as `like`'),
            DB::raw('sum(case when action_type = 2 then 0 END) as `follow`'),
            DB::raw('sum(case when action_type = 3 then 0 END) as `followBack`')
        )->groupBy('account_id');
}

with 子查询

$userAddedPagesList = auth()->user()->instagramPages()->with([
        'history' => function ($query) {
            $query->select('*')
                ->selectSub(function ($query) {
                    return $query->selectRaw('SUM(action_type)')
                        ->where('action_type', '=', '1');
                }, 'like')
                ->selectSub(function ($query) {
                    return $query->selectRaw('SUM(action_type)')
                        ->where('action_type', '=', '2');
                }, 'follow')
                ->selectSub(function ($query) {
                    return $query->selectRaw('SUM(action_type)')
                        ->where('action_type', '=', '3');
                }, 'followBack');

            $query->groupBy('users.id');   //<-- add this
        }
    ]
)->get();

模型观察者

有时候我们需要在一个表更改后,触发某个事件,最常见的比如,首页推荐商品 1 更改了,需要清空所有首页商品缓存。

首先我们需要在建立一个观察者类,比如 App\Model\Observers\ProjectAttrObservers,当然放在什么地方或者叫什么名都可以自己定义。

里面的代码可能是

<?php

namespace App\Models\Observers;

class GoodsObservers
{
    public function saved(\App\Models\Goods $model)
    {
        \Cache::forget('topGoodsList');
    }
}
作用就是,当 goods 表新增和修改的时候,saved 这个方法就会触发,然后清空缓存

之后在 AppServiceProvider,当然你也可以新建一个比如 ObserverServiceProvider。

<?php

namespace App\Providers;

use App\Models\Goods;

use Illuminate\Support\ServiceProvider;

class ObserverServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Goods::observe(new \App\Models\Observers\GoodsObservers());
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

}

这个的作用是在程序启动的时候,监听 GoodsObservers 这个类 最后,将 ObserverServiceProvider 放到 config/app.php 的providers 数组中即可

枚举

https://segmentfault.com/a/1190000021088622

when的使用

实例一

// 下面这个代码when后面跟的第一个参数是true和false,例子是true,所以执行的是前面的匿名函数,同时要用use传参进去才行哦,
 // 第二个匿名就是否则执行的意思,
 $status = 1;
 $examList = Exams::when($status == 1,function ($query) use ($categoryId){
            $query->whereIn('category_id',$categoryId);
        },function ($query) use ($categoryId2){
            $query->whereIn('category_id',$categoryId2);
        })->select('examid','exam','question_sort')->get();

实例二:

$name = $request->get('name');               //活动标题
$start_time = $request->get('start_time');         //活动开始时间
$user_name = $request->get('user_name');          //发布者
$limit = (int) $request->get('limit', 15);
$offset = (int) $request->get('offset', 0);
$data=ActiveJieSuan::with(['user' => function ($query) {$query->select('id','name');},
  'active'=> function ($query) {$query->select('id','name','start');}])
  ->when($name, function ($query) use ($name) {
   return $query->whereHas('active', function ($query) use ($name) {
     return $query->where('name', 'like', '%'.$name.'%');
   });
  })
  ->when($user_name, function ($query) use ($user_name) {
   return $query->whereHas('user', function ($query) use ($user_name) {
     return $query->where('name', 'like', '%'.$user_name.'%');
   });
  })
  ->when($start_time, function ($query) use ($start_time) {
   return $query->whereHas('active', function ($query) use ($start_time) {
     return $query->where('start', '>=', $start_time);
   });
  })
  ->limit($limit)
  ->offset($offset)
  ->orderBy('id', 'desc')
  ->paginate()->toArray();

Eloquent ORM 模型中添加自定义值

https://learnku.com/laravel/t/3521/add-custom-values-in-the-eloquent-orm-model

统计每天订单

 Order::query()
                ->selectRaw('DATE_FORMAT(paid_at,"%m-%d") as day')
                ->selectRaw('COUNT(*) as count')
                ->where('paid_at', '>', $time)
                ->where('paid_at', '<', date('Y-m-d 00:00:00', time()))
                ->groupBy('day')
                ->get()->toArray();

扩展:

              'period_amount' => 'SUM(case when payment_method = "platform_period" THEN order_amount end)',
                'period_num' => 'COUNT(case when payment_method= "platform_period" THEN 1 end)',

新增时的操作

    protected static function boot()
    {
        parent::boot();
        // 监听模型创建事件,在写入数据库之前触发
        static::creating(function ($model) {
            // 如果模型的 no 字段为空
            if (!$model->no) {
                // 调用 findAvailableNo 生成订单流水号
                $model->no = static::findAvailableNo();
                // 如果生成失败,则终止创建订单
                if (!$model->no) {
                    return false;
                }
            }
        });
    }
查询中加条件
   ->select([$time > 1 ? DB::raw('DATE(created_at) as time') : DB::raw('DATE_FORMAT(created_at,\'%H\') as time'), DB::raw('COUNT("*") as count')])
for update

For update Laravel

 类似资料: