2026-01-21 05:31:04
ThinkPHP模型通过继承thinkModel类定义,关联查询通过模型方法配置后使用with方法实现预载入。 以下是详细说明:
一、模型定义方法基础定义
模型类需继承thinkModel,默认命名空间为appmodel。
模型名自动对应数据表:模型名转为下划线小写并复数形式(如User对应users表)。
可通过protected $table手动指定表名(如protected $table = 'user';)。
namespace appmodel;use thinkModel;class User extends Model { // 指定表名(可选) protected $table = 'user';}常见配置项
主键:protected $pk = 'id';(默认已配置为id)。
时间戳:
protected $autoWriteTimestamp = true;开启自动写入。
protected $createTime = 'create_at';自定义创建时间字段。
protected $updateTime = 'update_at';自定义更新时间字段。
字段过滤:protected $field = ['id', 'name', 'email'];限制允许操作的字段。
class User extends Model { protected $autoWriteTimestamp = true; protected $createTime = 'create_at'; protected $updateTime = 'update_at'; protected $field = ['id', 'name', 'email'];}ThinkPHP支持四种关联类型,需在模型中通过方法定义:
一对一(hasOne)
示例:用户与详情表(User → Profile)。
在User模型中定义:public function profile() { return $this->hasOne('appmodelProfile', 'user_id', 'id');}
一对多(hasMany)
示例:用户与文章表(User → Article)。
在User模型中定义:public function articles() { return $this->hasMany('appmodelArticle', 'user_id', 'id');}
属于(belongsTo)
示例:文章属于用户(Article → User)。
在Article模型中定义反向关联:public function user() { return $this->belongsTo('appmodelUser', 'user_id', 'id');}
多对多(belongsToMany)
示例:用户与角色表(通过中间表user_role关联)。
在User模型中定义:public function roles() { return $this->belongsToMany('appmodelRole', 'user_role');}
基础预载入
使用with()方法预载入关联数据,避免N+1查询问题。
示例:查询用户及其所有文章:$user = User::with('articles')->find(1);echo $user->name;foreach ($user->articles as $article) { echo $article->title;}
多关联预载入
同时预载入多个关联:$user = User::with(['articles', 'profile'])->find(1);
关联条件查询
在with()中传递闭包添加条件:$user = User::with(['articles' => function($query) { $query->where('status', 1)->order('create_at', 'desc');}])->find(1);
一对一直接访问
一对一关联可直接通过属性访问(自动触发查询):$profile = $user->profile; // 自动查询Profile表
多对多关联查询
示例:查询用户的所有角色名:$user = User::with('roles')->find(1);foreach ($user->roles as $role) { echo $role->name;}
通过合理定义模型和关联关系,结合with()方法,可高效实现复杂数据查询,提升代码可维护性。