ThinkPHP6模型关联实战:5个高级关联查询技巧
1. 基础一对一关联
用户与用户档案关联:
// User模型
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
// Profile模型
class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
// 控制器中使用
$user = User::with('profile')->find(1);
echo $user->profile->address;
2. 一对多关联查询
商品与商品评论关联:
// Product模型
class Product extends Model
{
public function comments()
{
return $this->hasMany(Comment::class)
->order('create_time', 'desc')
->limit(5);
}
}
// 控制器中使用
$product = Product::with(['comments' => function($query) {
$query->where('status', 1);
}])->find($id);
3. 多对多关联处理
用户与角色多对多关联:
// User模型
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class, 'user_role');
}
}
// 控制器中使用
// 获取用户所有角色
$user = User::with('roles')->find(1);
// 添加角色关联
$user->roles()->attach([1, 2, 3]);
// 同步角色关联
$user->roles()->sync([1, 3]);
4. 关联统计查询
统计商品评论数量:
// 获取商品列表及评论数
$products = Product::withCount('comments')
->order('comments_count', 'desc')
->select();
// 获取评论数大于10的商品
$products = Product::has('comments', '>', 10)
->select();
关联类型 | 方法 | 适用场景 |
---|---|---|
一对一 | hasOne/belongsTo | 用户-档案 |
一对多 | hasMany/belongsTo | 文章-评论 |
多对多 | belongsToMany | 用户-角色 |
5. 关联预加载优化
嵌套关联预加载:
// 获取订单及关联的用户和商品
$orders = Order::with([
'user' => function($query) {
$query->field('id,name');
},
'products' => function($query) {
$query->field('id,title,price')
->withPivot('quantity');
}
])->select();
// 延迟预加载
$orders = Order::select();
$orders->load(['user', 'products']);
合理使用ThinkPHP6的模型关联可以大幅简化复杂数据查询,提高开发效率,是构建中大型项目的必备技能。