首页 > 解决方案 > 如何在 clancats hydrahon update() 中传递空值?

问题描述

根据下面的代码,我需要为数据库列传递一个空值:

$birthdate = null;

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

但是会产生错误:

在此处输入图像描述

这个怎么做 ?

注意:更新是clancats hydrahon的一种方法。

我相信问题出现在库代码的那部分。

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;
}

标签: php

解决方案


首先; 永远不要更改供应商目录中的文件。 供应商目录不应在您的项目中进行版本控制,并且任何更改在生产或其他人中都将不可用。

作为答案;我认为使用数组应该可以。也因为它写在评论中

// 当参数 2 不为空时,我们假设只传递了一个集合
// 比如: set( 'name', 'Lu' ); 而不是set(array('name' => 'Lu'));

$birthdate = null;

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

原因

if (empty($param1)) { // false: because it's not empty. We pass on
   return $this;
}
if ( !is_null( $param2 ) ) { // false: because it IS null. We pass on
   $param1 = array( $param1 => $param2 );
}

在这一点上,我们有$param1 = ['birthdate' => null]and$param2 = null 但是这一次,我们没有字符串。我们有一个数组。

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

更进一步,我认为你甚至可以这样做


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

推荐阅读