一、一对一关联
version > 5.0.4
定义一对一关联,例如,一个用户都有一个个人资料,我们定义User模型如下:
namespace app\index\model;
use think\Model;
class User extends Model
{
public function profile()
{
return $this->hasOne('Profile')
}
}
二、hasOne参数详解
hasOne('关联模型名', '外键名', '主键名', ['模型别名定义'], 'join 类型');
// 默认的join类型为INNER
namespace app\index\model;
use think\Model;
class User extends Model
{
public function profile()
{
return $this->hasOne('Profile')->field('id,name,email');
}
}
PS:如果使用的是join方式的关联,不支持指定field字段
三、关联查找
定义好关联之后,就可以使用下面的方法获取关联数据
$user = User::get(1);
echo $user->profile->email;
如果要根据关联表的查询条件查询当前模型的数据,可以使用hasWhere 方法,例如:
$user = User::hasWhere('profile',['email'=>'thinkphp@qq.com'])->find();
echo $user->name;
默认情况下,我们使用的是 user_id 作为外键关联,如果不是的话则需要在关联定义的时候指定,例如:
namespace app\index\model;
use think\Model;
class User extends Model
{
public function profile()
{
return $this->hasOne('Profile','uid');
}
}
四、关联新增
$user = User::get(1);
// 如果还没有关联数据 则进行新增
$user->profile()->save(['email' => 'thinkphp']);
系统会自动把当前模型的主键传入profile模型
五、关联更新
和新增一样使用 save 方法进行更新关联数据
$user = User::get(1);
$user->profile->email = 'thinkphp';
$user->profile->save();
// 或者
$user->profile->save(['email' => 'thinkphp']);