在 ThinkPHP6 中,可以通过 'withCount' 方法来统计一对多关联中全部加起来的数量。

假设有两个模型 'User' 和 'Order','User' 模型有多个 'Order' 模型的关联,可以在 'User' 模型的关联方法中使用 'withCount' 方法来统计全部加起来的数量。

// User模型
namespace app\model;

use think\Model;

class User extends Model
{
    // 定义User模型与Order模型的一对多关联
    public function orders()
    {
        return $this->hasMany(Order::class);
    }
}

// Order模型
namespace app\model;

use think\Model;

class Order extends Model
{
    // 定义Order模型与User模型的多对一关联
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

// 在控制器中使用
use app\model\User;

$user = User::withCount('orders')->find($id);
$totalOrders = $user->orders_count;

在上述代码中,'withCount('orders')' 会将统计的结果存储在 'orders_count' 字段中,可以通过 '$user->orders_count' 来获取全部加起来的数量。

ThinkPHP6 一对多关联统计数量:withCount方法详解

原文地址: https://www.cveoy.top/t/topic/pRM1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录