关联之一对一关联
一对一关联
定义
定义一对一关联,例如,一个用户都有一个个人资料,我们定义User模型如下:
namespace appindexmodel;
use thinkModel;
class User extends Model
{
public function profile()
{
return $this->hasOne('Profile');
}
}
use thinkModel;
class User extends Model
{
public function profile()
{
return $this->hasOne('Profile');
}
}
hasOne方法的参数包括:
hasOne('关联模型名','外键名','主键名',['模型别名定义'],'join类型');
默认的join类型为INNER。
V5.0.3+版本开始,可以支持为关联模型定义需要查询的字段,例如:
namespace appindexmodel;
use thinkModel;
class User extends Model
{
public function profile()
{
return $this->hasOne('Profile')->field('id,name,email');
}
}
use thinkModel;
class User extends Model
{
public function profile()
{
return $this->hasOne('Profile')->field('id,name,email');
}
}
关联查找
定义好关联之后,就可以使用下面的方法获取关联数据:
$user = User::find(1);
// 输出Profile关联模型的email属性
echo $user->profile->email;
// 输出Profile关联模型的email属性
echo $user->profile->email;
默认情况下, 我们使用的是user_id 作为外键关联,如果不是的话则需要在关联定义的时候指定,例如:
namespace appindexmodel;
use thinkModel;
class User extends Model
{
public function profile()
{
return $this->hasOne('Profile','uid');
}
}
use thinkModel;
class User extends Model
{
public function profile()
{
return $this->hasOne('Profile','uid');
}
}
设置别名
如果你的模型名和数据库关键字冲突的话,可以设置别名,例如:
namespace appindexmodel;
use thinkModel;
class User extends Model
{
public function profile()
{
return $this->hasOne('Profile','uid')->setAlias(['user'=>'member']);
}
}
use thinkModel;
class User extends Model
{
public function profile()
{
return $this->hasOne('Profile','uid')->setAlias(['user'=>'member']);
}
}
关联新增
$user = User::find(1);
// 如果还没有关联数据 则进行新增
$user->profile()->save(['email' => 'thinkphp']);
// 如果还没有关联数据 则进行新增
$user->profile()->save(['email' => 'thinkphp']);
系统会自动把当前模型的主键传入profile模型。
关联更新
和新增一样使用save方法进行更新关联数据。
$user = User::find(1);
$user->profile->email = 'thinkphp';
$user->profile->save();
// 或者
$user->profile->save(['email' => 'thinkphp']);
$user->profile->email = 'thinkphp';
$user->profile->save();
// 或者
$user->profile->save(['email' => 'thinkphp']);
定义相对的关联
我们可以在Profile模型中定义一个相对的关联关系,例如:
namespace appindexmodel;
use thinkModel;
class Profile extends Model
{
public function user()
{
return $this->belongsTo('User');
}
}
use thinkModel;
class Profile extends Model
{
public function user()
{
return $this->belongsTo('User');
}
}
belongsTo的参数包括:
belongsTo('关联模型名','外键名','关联表主键名',['模型别名定义'],'join类型');
默认的关联外键是user_id,如果不是,需要在第二个参数定义
namespace appindexmodel;
use thinkModel;
class Profile extends Model
{
public function user()
{
return $this->belongsTo('User','uid');
}
}
use thinkModel;
class Profile extends Model
{
public function user()
{
return $this->belongsTo('User','uid');
}
}
我们就可以根据档案资料来获取用户模型的信息
$profile = Profile::find(1);
// 输出User关联模型的属性
echo $profile->user->account;
// 输出User关联模型的属性
echo $profile->user->account;