php has,thinkphp中hasOne函数概述

一、一对一关联

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']);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值