How to pass a null value in the update() method of clancats hydrahon?

Asked

Viewed 77 times

1

I need to pass a null value to a column (date type) of the mysql database, according to the following code:

$birthdate = null;

User::update()
->set('name', $name)
->set('email', $email)
->set('birthdate', $birthdate)                
->where('id', $id)
->execute();

However this error is generated below:

inserir a descrição da imagem aqui

It seems that hydrahon does not accept passing a null value in its update method().

My question would be: How would I insert that null, in the bank column, via the Hydrahon update() method ?

I will add the part of lib code that is pointed as the reason for the error:

public function set($param1, $param2 = null)
{
// do nothing if we get nothing
if (empty($param1))
{
   return $this;
}
        
// when param 2 is not null we assume that only one set is passed
// like: set( 'name', 'Lu' ); instead of set( array( 'name' => 'Lu' ) );
if ( !is_null( $param2 ) )
{
   $param1 = array( $param1 => $param2 );
}
        
// merge the new values with the existing ones.
$this->values = array_merge( $this->values, $param1 ); 
        
// return self so we can continue running the next function
return $this;
}

1 answer

5


(I don’t speak English. I used Google Translator to help answer this question. See the original answer on:)) Original Answer in english

I think using an array should work. And also why is writing in the comment

// when param 2 is not null we assume that only one set is passed
// like: set( 'name', 'Lu' ); Instead of set( array( 'name' => 'Lu' ) );

$birthdate = null;

User::update()
->set('name', $name)
->set('email', $email)
->set(['birthdate' => $birthdate]) // como isso            
->where('id', $id)
->execute();

Why

if (empty($param1)) { // false: porque não está vazio. Nós passamos
   return $this;
}
if ( !is_null( $param2 ) ) { // false: porque é null. Nós passamos
   $param1 = array( $param1 => $param2 );
}

At this point, we have $param1 = ['birthdate' => null] and $param2 = null But this time, we don’t have a string. We have an array.

 // $this->values = array_merge( [], ['birthdate' => null] ); 
    $this->values = array_merge( $this->values, $param1 ); 

Going further, I think you can even do so

User::update()
->set([
    'name'      => $name,
    'email'     => $email,
    'birthdate' => $birthdate,
 ])             
->execute();
  • 1

    Thank you very much. Your reply helped me a lot and will help other users.

  • That was the real difference. ->Sep(['birthdate' => $birthdate])

  • I updated my answer, forgot the bonus

Browser other questions tagged

You are not signed in. Login or sign up in order to post.