我正在尝试使用->delete()
通过关联模型删除数据库条目,但该条目不会被删除。
我尝试将表单从POST更改为DELETE,但这没有任何区别。围绕SO的研究也没有产生任何结果。
首选我希望避免使用似乎有用的Model::destroy($ids)
,。
路线方法:
// Delete an asset
public function getDelete($id)
{
// Try to find the asset, throw exception if not found
$asset = Asset::findOrFail($id);
$this->layout->title = 'Delete an asset';
$this->layout->content = View::make('asset.delete')
->with('assetID', $id);
}
// Delete the actual asset
public function postDelete()
{
$id = Input::get('AID');
// Try to find the asset, throw exception if not found
$asset = Asset::findOrFail($id);
// Attempt to delete it
if($asset->delete())
{
return Redirect::route('asset')
->with('success', 'The asset has been deleted succesfully!');
}
return Redirect::route('asset')
->with('failure', 'The asset could not be deleted. Please try again.');
}
路线:
/* Route to deleting an asset
* Shorthand: URL::route('deleteAsset')
* Uses AssetController::getDelete
*/
Route::get('/asset/delete/{id}', array(
'as' => 'deleteAsset',
'uses' => 'AssetController@getDelete'
));
/* Route to actually deleting an asset
* Shorthand: URL::route('deleteAssetPost')
* Uses AssetController::postDelete
*/
Route::delete('/asset/delete/', array(
'as' => 'deleteAssetPost',
'uses' => 'AssetController@postDelete'
));
模特:
class Asset extends Eloquent
{
public $timestamps = false;
protected $table = 'Asset';
protected $primaryKey = 'AID';
protected $fillable = array('ACID', 'AKID', 'AATID', 'APurchaseDate');
// Retrieve the customer's name associated with the asset
public function customer()
{
return $this->hasOne('Customer', 'CID', 'ACID');
}
// Retrieve the asset type that is associated with the asset
public function assetType()
{
return $this->hasOne('AssetType', 'ATID', 'AATID');
}
// Get the customer name
public function getCustomerName()
{
return $this->customer()->first()->CName;
}
// Get the asset type name
public function getAssetTypeName()
{
return $this->assetType()->first()->ATName;
}
// Get the associated key
public function getKey()
{
return $this->AKID === -1 ? 'nvt' : $this->AKID;
}
// Get the purchase date in readable form
public function getPurchaseDate($format = 'd-m-Y')
{
return date($format, strtotime($this->APurchaseDate));
}
}
根据控制器,删除成功并给出成功消息。
不会抛出任何错误。
[编辑]
有谁知道我在这里缺少什么来使这项工作?
记录查询后,使用$asset->delete()
执行以下查询:
select * from `Asset` where `AID` = ? limit 1
delete from `Asset` where `AID` = ?
我用Asset::destroy($id)
尝试了同样的事情,其结果是:
select * from `Asset` where `AID` = ? limit 1
select * from `Asset` where `AID` in (?)
delete from `Asset` where `AID` = ?
答案 0 :(得分:5)
在聊天中进行了一些讨论后,我们意识到代码在模型上定义了一个getKey()
方法,该方法用于特定于域的目的。然而,这实际上是Eloquent在所有模型上定义的方法,并且它使用它非常重要。在这种情况下,Eloquent的delete
方法调用getKey()
来确定模型的ID。
非错误的原因是虽然删除本身无法删除(因为它试图删除ID为'nvt'的模型),但从技术上讲,它并没有做任何值得错误的事情。完全有效的代码/ SQl:DELETE FROM `table` WHERE `id` = 'nvt';