在 ThinkPHP 中模型關聯刪除官方文檔只提到了主子表數據一起刪除的方法。
即使用together
方法,但在不刪除主表
只刪除子表
的時候遇到問題了。
正常執行(TP5)
以下代碼在 TP 5.0.24 中是可以正常刪除子表數據的:
<?php
namespace app\index\controller;
use app\common\model\Article;
class Index
{
public function index()
{
$data = Article::get(1, ['image']);
$data->image()->delete();
return json($data);
}
}
問題代碼(TP6)
而到了 TP 6 代碼有點變化,但基本是一樣的操作,卻會報錯:
沒有條件不會執行刪除操作
<?php
namespace app\controller;
use app\BaseController;
use app\model\Article;
class Index extends BaseController
{
public function index()
{
$data = Article::with(['image'])->find(1);
$data->image()->delete();
return json($data);
}
}
報錯詳情
解決方案
說實話我認爲這是 bug,臨時我的方案是
$data->image->delete();
參考鏈接
TP官網討論:http://www.thinkphp.cn/topic/68775.html