ThinkPHP6模型作用域实战:优雅封装常用查询条件 | ThinkPHP高级技巧

2025-07-11 0 315

ThinkPHP6模型作用域实战:优雅封装常用查询条件

ThinkPHP6的模型作用域功能允许开发者将常用查询条件封装为可复用的方法,大幅提升代码的可维护性。本文将通过电商系统案例展示如何高效利用这一特性。

1. 基础作用域定义

在商品模型中封装常用查询条件:

// app/model/Product.php
namespace appmodel;

class Product extends thinkModel
{
// 定义全局作用域
protected $globalScope = [‘status’];

// 上架商品作用域
public function scopeStatus($query)
{
$query->where(‘status’, 1);
}

// 价格区间作用域
public function scopePriceBetween($query, $min, $max)
{
$query->whereBetween(‘price’, [$min, $max]);
}
}

2. 作用域链式调用

组合多个作用域构建复杂查询:

// 查询价格在100-500元的热销上架商品
$products = Product::scope(‘priceBetween’, [100, 500])
->where(‘sales’, ‘>’, 1000)
->order(‘sales’, ‘desc’)
->select();

3. 动态作用域应用

根据参数动态应用不同作用域:

public function search(Request $request)
{
$query = Product::scope(‘status’);

if ($request->has(‘category_id’)) {
$query->where(‘category_id’, $request->param(‘category_id’));
}

if ($request->has(‘price_range’)) {
$priceRange = explode(‘-‘, $request->param(‘price_range’));
$query->scope(‘priceBetween’, $priceRange);
}

return $query->paginate(10);
}

最佳实践: 将业务相关的查询条件封装为作用域,保持控制器代码简洁。

4. 实际案例:多状态订单查询

在订单模型中封装各种状态查询:

// app/model/Order.php
public function scopePending($query)
{
$query->where(‘status’, 0)->where(‘pay_status’, 0);
}

public function scopePaid($query)
{
$query->where(‘status’, 0)->where(‘pay_status’, 1);
}

public function scopeCompleted($query)
{
$query->where(‘status’, 1);
}

public function scopeRecent($query, $days = 7)
{
$query->whereTime(‘create_time’, ‘>=’, date(‘Y-m-d’, strtotime(“-$days day”)));
}

// 使用示例
$recentPaidOrders = Order::scope(‘paid’)->scope(‘recent’)->select();

ThinkPHP6的模型作用域为数据查询提供了优雅的封装方案,通过合理的抽象可以显著提升代码复用率和可读性。

ThinkPHP6模型作用域实战:优雅封装常用查询条件 | ThinkPHP高级技巧
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

淘吗网 thinkphp ThinkPHP6模型作用域实战:优雅封装常用查询条件 | ThinkPHP高级技巧 https://www.taomawang.com/server/thinkphp/218.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务