public function attach($data, $pivot = [])
{
if (is_array($data)) {
// 保存关联表数据
$model = new $this->model();
$model->save($data);
$id = $model->getLastInsID();
} elseif (is_numeric($data) || is_string($data)) {
// 根据关联表主键直接写入中间表
$id = $data;
} elseif ($data instanceof Model) {
// 根据关联表主键直接写入中间表
$relationFk = $data->getPk();
$id = $data->{$relationFk};
}
if ($id) {
// 保存中间表数据
$pk = $this->parent->getPk();
$pivot[$this->localKey] = $this->parent->{$pk};
$pivot[$this->foreignKey] = $id;
$query = clone $this->parent->db();
return $query->table($this->middle)->insert($pivot);
} else {
throw new Exception('miss relation data');
}
}