开发文档 v2.x

绑定/加载数据

更新时间:2024年7月26日 14:39 浏览:401

行模型可以绑定数据(GET, POST, 或者一个数组, 对象),或从数据库加载数据。

  • bind - 绑定数据
  • load - 按主锓加载记录
  • loadBy - 按条件加载记录

 

bind - 绑定数据

public function bind($data): Tuple

参数:

  • array | object $data - 要绑定的数据数组或对象

返回值:

  • Tuple - 行模型本身

 

可绑定 GET, POST, 或者一个数组, 对象

 

代码示例:

$arr = [
  'name' => '马云',
  'age' => 50,
];
// 绑定数组形式数据,并向数据库中插入一条记录
Be::getTuple('user')->bind($arr)->insert();

$obj = new \stdClass();
$obj->name = '马云';
$obj->age = 50;
// 绑定对象形式数据,并向数据库中插入一条记录
Be::getTuple('user')->bind($obj)->insert();

// 也可直接绑定 POST 数据
$post = Be::gerRequest()->post();
Be::getTuple('user')->bind($post)->insert();

 

load - 按主锓加载记录

public function load($primaryKeyValue): Tuple

参数:

  • string | array $primaryKeyValue - 主锓的值,当为数组时格式为键值对

返回值:

  • Tuple - 行模型本身

 

代码示例:

$tuple = Be::getTuple('user');
try {
  $tuple->load('f69e75bf-9e18-11ec-a3cb-0242ac180065');

  // 当表为联合主键时,需使用键值对
  /*
  $tuple->load([
    'id' => 'f69e75bf-9e18-11ec-a3cb-0242ac180065',
    'name' => '马云',
  ]);
  */
} catch (\Throwable $t) {
  throw new ServiceException('用户不存在!');
}

// $tuple->name;
// $tuple->age;

// 修改行记录
$tuple->age = 51;

// 可以加载完数据后,绑定 POST 数据
$post = Be::gerRequest()->post();
$tuple->bind($post);

// 更新数据库里的记录
$tuple->update();

 

loadBy - 按条件加载记录

public function loadBy($field, $value = null): Tuple

参数:

  • string | array $field - 要加载数据的键名或銉值对
  • string $value 要加载的键的值

返回值:

  • Tuple - 行模型本身

 

当 $value === null 时, $field 必须为键值对数据,按指定的键值对加载,

 

代码示例:

$tuple = Be::getTuple('user');
try {
  $tuple->loadBy('name', '马云');
} catch (\Throwable $t) {
  throw new ServiceException('用户不存在!');
}

// 修改行记录
$tuple->age = 51;
$tuple->update();


// 按指定的键值对条件加载
$tuple = Be::getTuple('user');
try {
  $tuple->loadBy([
    'name' => '马云',
    'age' => 50,
  ]);
} catch (\Throwable $t) {
  throw new ServiceException('用户不存在!');
}

 

导航