FuelPHP:级联删除不起作用
FuelPHP: Cascading Delete Not Working
我有两个 table。一个是类别,该类别有很多提名。
Table 类别
protected static $_has_many = array(
'nominations' => array(
'key_from' => 'id',
'key_to' => 'category_id',
'model_to' => 'Model_Nominations',
'cascade_save' => true,
'cascade_delete'=> true
)
);
Table 提名
protected static $_belongs_to = array(
'categories' => array(
'key_from' => 'category_id',
'key_to' => 'id',
'model_to' => 'Model_Categories',
'cascade_save' => true,
'cascade_delete'=> true
)
);
当我删除类别时:
public static function delete_($args)
{
$q = Model_Categories::query()
->where('id','=',$args['id']);
if($q->count() > 0){
$q->delete();
return true;
}
return false;
}
它不会删除提名 table 中的提名条目,即使 cascade_delete
设置为 true。我错过了什么?
你的逻辑是错误的。
在您的示例中,$q
是一个 ORM 查询对象,因此 delete 仅运行一个删除查询:DELETE FROM categories WHERE id = ?
.
如果你想删除一个对象及其关系,你需要获取一个模型对象及其关系。它不会级联到未加载的关系中。
public static function delete_($args)
{
if ($result = Model_Categories::find($args['id'], array('related'=>array('nominations')))
{
return $result->delete();
}
return false;
}
我有两个 table。一个是类别,该类别有很多提名。
Table 类别
protected static $_has_many = array(
'nominations' => array(
'key_from' => 'id',
'key_to' => 'category_id',
'model_to' => 'Model_Nominations',
'cascade_save' => true,
'cascade_delete'=> true
)
);
Table 提名
protected static $_belongs_to = array(
'categories' => array(
'key_from' => 'category_id',
'key_to' => 'id',
'model_to' => 'Model_Categories',
'cascade_save' => true,
'cascade_delete'=> true
)
);
当我删除类别时:
public static function delete_($args)
{
$q = Model_Categories::query()
->where('id','=',$args['id']);
if($q->count() > 0){
$q->delete();
return true;
}
return false;
}
它不会删除提名 table 中的提名条目,即使 cascade_delete
设置为 true。我错过了什么?
你的逻辑是错误的。
在您的示例中,$q
是一个 ORM 查询对象,因此 delete 仅运行一个删除查询:DELETE FROM categories WHERE id = ?
.
如果你想删除一个对象及其关系,你需要获取一个模型对象及其关系。它不会级联到未加载的关系中。
public static function delete_($args)
{
if ($result = Model_Categories::find($args['id'], array('related'=>array('nominations')))
{
return $result->delete();
}
return false;
}