Welcome Guest, Not a member yet? Register   Sign In
Multiple primary keys for protected $primaryKey
#9

Here's my first stab at doing an override in doInsert and doUpdate.

Anyone have any feedback?
 
PHP Code:
protected function doUpdate($id NULL$data NULL)
 : 
bool {
 
$escape $this->escape;
 
$this->escape = [];

 
$builder $this->builder();

 if (
$id) {
 if (
is_array($id) && is_array($this->primaryKey)) {
 for (
$index 0$index count($this->primaryKey); $index++) {
 
$primary_key $this->primaryKey[$index];
 
$value $id[$primary_key];
 
$full_column sprintf("%s.%s"$this->table$primary_key);
 
$builder $builder->whereIn($full_column, array($value));
 }
 } else {
 
$builder $builder->whereIn($this->table '.' $this->primaryKey$id);
 }
 }

 
// Must use the set() method to ensure to set the correct escape flag
 
foreach ($data as $key => $val) {
 
$builder->set($key$val$escape[$key] ?? NULL);
 }

 return 
$builder->update();
 }

 protected function 
doInsert(array $data)
 {
 
$escape $this->escape;
 
$this->escape = [];

 
// Require non empty primaryKey when
 // not using auto-increment feature

 
if (!$this->useAutoIncrement) {
 if (
is_array($this->primaryKey)) {
 foreach (
$this->primaryKey as $primary_key) {
 if (empty(
$data[$primary_key])) {
 throw 
DataException::forEmptyPrimaryKey('insert');
 }
 }
 } else {
 
/** @noinspection PhpIllegalArrayKeyTypeInspection */
 
if (!is_array($this->primaryKey) && empty($data[$this->primaryKey])) {
 throw 
DataException::forEmptyPrimaryKey('insert');
 }
 }
 }

 
$builder $this->builder();

 
// Must use the set() method to ensure to set the correct escape flag
 
foreach ($data as $key => $val) {
 
$builder->set($key$val$escape[$key] ?? NULL);
 }

 
$result $builder->insert();

 
// If insertion succeeded then save the insert ID
 
if ($result) {
 if (
is_array($this->primaryKey)) {
 return 
FALSE;
 } else {
 
$this->insertID = !$this->useAutoIncrement $data[$this->primaryKey] : $this->db->insertID();
 }
 }

 return 
$result;
 } 
Reply


Messages In This Thread
RE: Multiple primary keys for protected $primaryKey - by john_brahy.com - 03-02-2022, 09:41 PM



Theme © iAndrew 2016 - Forum software by © MyBB