EloquentDeleteTest.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\SoftDeletes;
  5. use Illuminate\Database\Schema\Blueprint;
  6. use Illuminate\Support\Facades\Schema;
  7. use Illuminate\Tests\Integration\Database\Fixtures\Post;
  8. class EloquentDeleteTest extends DatabaseTestCase
  9. {
  10. protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
  11. {
  12. Schema::create('posts', function (Blueprint $table) {
  13. $table->increments('id');
  14. $table->string('title')->nullable();
  15. $table->timestamps();
  16. });
  17. Schema::create('comments', function (Blueprint $table) {
  18. $table->increments('id');
  19. $table->string('body')->nullable();
  20. $table->integer('post_id');
  21. $table->timestamps();
  22. });
  23. Schema::create('roles', function (Blueprint $table) {
  24. $table->increments('id');
  25. $table->timestamps();
  26. $table->softDeletes();
  27. });
  28. }
  29. /** @group SkipMSSQL */
  30. public function testDeleteWithLimit()
  31. {
  32. for ($i = 1; $i <= 10; $i++) {
  33. Comment::create([
  34. 'post_id' => Post::create()->id,
  35. ]);
  36. }
  37. Post::latest('id')->limit(1)->delete();
  38. $this->assertCount(9, Post::all());
  39. Post::join('comments', 'comments.post_id', '=', 'posts.id')
  40. ->where('posts.id', '>', 8)
  41. ->orderBy('posts.id')
  42. ->limit(1)
  43. ->delete();
  44. $this->assertCount(8, Post::all());
  45. }
  46. public function testForceDeletedEventIsFired()
  47. {
  48. $role = Role::create([]);
  49. $this->assertInstanceOf(Role::class, $role);
  50. Role::observe(new RoleObserver);
  51. $role->delete();
  52. $this->assertNull(RoleObserver::$model);
  53. $role->forceDelete();
  54. $this->assertEquals($role->id, RoleObserver::$model->id);
  55. }
  56. }
  57. class Comment extends Model
  58. {
  59. public $table = 'comments';
  60. protected $fillable = ['post_id'];
  61. }
  62. class Role extends Model
  63. {
  64. use SoftDeletes;
  65. public $table = 'roles';
  66. protected $guarded = [];
  67. }
  68. class RoleObserver
  69. {
  70. public static $model;
  71. public function forceDeleted($model)
  72. {
  73. static::$model = $model;
  74. }
  75. }