CakePHP 从父模型更新子模型
CakePHP update a child model from parent
我目前正在努力获取关联模型以使用 CakePHP 2.3 进行更新。我希望父模型处于非活动状态,子模型记录处于非活动状态。我的公司模型中有以下方法,它只更新父模型(而不是子模型)。实现这一目标的最佳方法是什么?我尝试将方法移至子对象,但没有任何区别。
class Company extends AppModel {
public $hasMany = array(
'CompaniesUser' => array(
'className' => 'CompaniesUser'
)
);
function updateToInactive( $companyId ){
$data = array(
array(
'Company' => array(
'id' =>$companyId,
'active' => 0,
'payment_active'=> 0
),
'CompaniesUser' => array(
'company_id' =>$companyId,
'active' => 0)
)
);
$this->saveAll($data);
}
}
我的公司用户模型如下所示:(属于公司)
class CompaniesUser extends AppModel {
public $belongsTo = array(
'Company' => array(
'className' => 'Company',
'foreignKey' => 'company_id'
)
);
你的 $data
数组在我看来不适合 hasMany
关系。它应该看起来更像这样:-
$data = array(
'Company' => array(
'id' =>$companyId,
'active' => 0,
'payment_active'=> 0
),
'CompaniesUser' => array(
array(
'company_id' =>$companyId,
'active' => 0
)
)
);
$this->saveAssociated($data);
使用 saveAssociated()
比 saveAll()
更好,因为您正在保存关联数据。
更新
除非您将主键与保存数据一起传递,否则以上不会更新现有的 CompaniesUsers。您可以先保存公司,然后使用 updateAll()
更新相关公司的用户数据。如果你使用 updateAll()
你需要记住 escape the values being saved:-
// Update company
$data = array(
'id' =>$companyId,
'active' => 0,
'payment_active'=> 0
);
$this->save($data);
// Update company users
$this->CompaniesUser->updateAll(
array('CompaniesUser.active' => '"0"'),
array('CompaniesUser.company_id' => '"' . $companyId . '"')
);
我目前正在努力获取关联模型以使用 CakePHP 2.3 进行更新。我希望父模型处于非活动状态,子模型记录处于非活动状态。我的公司模型中有以下方法,它只更新父模型(而不是子模型)。实现这一目标的最佳方法是什么?我尝试将方法移至子对象,但没有任何区别。
class Company extends AppModel {
public $hasMany = array(
'CompaniesUser' => array(
'className' => 'CompaniesUser'
)
);
function updateToInactive( $companyId ){
$data = array(
array(
'Company' => array(
'id' =>$companyId,
'active' => 0,
'payment_active'=> 0
),
'CompaniesUser' => array(
'company_id' =>$companyId,
'active' => 0)
)
);
$this->saveAll($data);
}
}
我的公司用户模型如下所示:(属于公司)
class CompaniesUser extends AppModel {
public $belongsTo = array(
'Company' => array(
'className' => 'Company',
'foreignKey' => 'company_id'
)
);
你的 $data
数组在我看来不适合 hasMany
关系。它应该看起来更像这样:-
$data = array(
'Company' => array(
'id' =>$companyId,
'active' => 0,
'payment_active'=> 0
),
'CompaniesUser' => array(
array(
'company_id' =>$companyId,
'active' => 0
)
)
);
$this->saveAssociated($data);
使用 saveAssociated()
比 saveAll()
更好,因为您正在保存关联数据。
更新
除非您将主键与保存数据一起传递,否则以上不会更新现有的 CompaniesUsers。您可以先保存公司,然后使用 updateAll()
更新相关公司的用户数据。如果你使用 updateAll()
你需要记住 escape the values being saved:-
// Update company
$data = array(
'id' =>$companyId,
'active' => 0,
'payment_active'=> 0
);
$this->save($data);
// Update company users
$this->CompaniesUser->updateAll(
array('CompaniesUser.active' => '"0"'),
array('CompaniesUser.company_id' => '"' . $companyId . '"')
);