总结7.15 tp5关联
一对一关联,A表中一条数据对应B表中一条数据
class User extends Model{
public function profile()
{
return $this->hasOne('Profile')->field('id,name,email');
}}
//hasOne('关联模型名','外键名','主键名',['模型别名定义'],'join类型');
$user = User::get(1);
echo $user->profile->email;
//关联查找,输出Profile关联模型的email属性
$user = User::get(1);
$user->profile()->save(['email' => 'thinkphp']);
//关联新增,如果还没有关联数据 则进行新增
$user = User::get(1);
$user->profile->email = 'thinkphp';
$user->profile->save();
//关联更新
一对多关联,A表中一条数据对应B表多条数据
class Article extends Model {
public function comments()
{
return $this->hasMany('Comment');
}}
//hasMany('关联模型名','外键名','主键名',['模型别名定义']);
多对多关联,A表中一条数据对应B表多条数据并且B表中一条数据对应A表中多条数据
class User extends Model {
public function roles()
{
return $this->belongsToMany('Role');
}}
//belongsToMany('关联模型名','中间表名','外键名','当前模型关联键名',['模型别名定义']);