有三张表
1)user
2)course
3)buycourse 记录被购买课程 和 购买用户
course ->> buycourse 一对多
user ->> buycourse 一对多
hasMany('关联模型',['外键','主键']);
return $this->hasMany('Profile','user_id', 'id');
关联模型(必须):模型名或者模型类名
外键:关联模型外键,默认的外键名规则是当前模型名+_id
主键:当前模型主键,一般会自动获取也可以指定传入
class User extends Model{
protected $auto = ['create_time'];
protected $type = [
'create_time' => 'timestamp:Y/m/d H:m:s',
];
public function profile(){
return $this->hasOne('Profile');
}
public function buy(){
return $this->hasMany('app\model\Buycourse');
}
}
class Buycourse extends Model{
protected $auto = ['buytime'];
protected $type = [
'buy_time' => 'timestamp:Y/m/d H:m:s',
];
public function course(){
return $this->belongsTo('Course','course_id','id');
}
public function user(){
return $this->belongsTo('app\user\model\User');
}
}
class Course extends Model
{
protected $type = [
'create_time' => 'timestamp:Y/m/d H:m:s',
];
protected $auto = ['create_time'];
protected $insert = ['is_top' => 1];
// protected function setCreateTimeAttr(){
// return time();
// }
public function info()
{
return $this->hasMany('CourseInfo');
}
public function buyc(){
return $this->hasMany('app\model\Buycourse');
}
这样用buycourse实例就可以获取另外两张表字段
buycourse->user->profile->name (profile是user关联表可以这样访问字段)把查询结果存储到数组在输出到视图模版。
要多读两遍tp5和php手册
0条评论