本文實例講述了Laravel框架Eloquent ORM刪除數據操作。分享給大家供大家參考,具體如下:
這篇文章,以下三個知識點希望大家能夠掌握
如下:
- 通過模型刪除
- 通過主鍵值刪除
- 通過指定條件刪除
NO.1模型刪除
老樣子,我們先新建一個方法,然后輸入代碼。
1
2
3
4
5
6
7
8
9
10
11
12
|
namespace App\Http\Controllers; use App\Student; use Illuminate\Support\Facades\DB; class StudentController extends Controller { public function orm4() { $student = Student::find(7); //找到id為7的 $bool = $student -> delete (); //刪除 var_dump( $bool ); } } |
如果他顯示出了一個true,則證明刪除成功,如果沒有刪除成功,則報錯
NO.2通過主鍵值刪除
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
|
namespace App\Http\Controllers; use App\Student; use Illuminate\Support\Facades\DB; class StudentController extends Controller { public function orm4() { $num = Student::destroy(7); var_dump( $num ); } } |
如果他輸出一個數字1,說明刪除成功,受影響的刪除數據總數為1,當然,如果要刪除多條數據也很簡單,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
|
namespace App\Http\Controllers; use App\Student; use Illuminate\Support\Facades\DB; class StudentController extends Controller { public function orm2() { $num = Student::destroy(7,5); var_dump( $num ); } } |
效果如下:
這里說明我刪除了兩條數據
NO.3通過指定條件刪除
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
namespace App\Http\Controllers; use App\Student; use Illuminate\Support\Facades\DB; class StudentController extends Controller { public function orm2() { $num = Student::where( 'id' , '>' ,3) -> delete (); var_dump( $num ); } } |
這里,id大于三的都會刪除,我就不手動演示了
希望本文所述對大家基于Laravel框架的PHP程序設計有所幫助。
原文鏈接:https://blog.csdn.net/weixin_44596681/article/details/89135919