EloquentTouchParentWithGlobalScopeTest.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database\EloquentTouchParentWithGlobalScopeTest;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Support\Facades\Schema;
  6. use Illuminate\Support\Str;
  7. use Illuminate\Tests\Integration\Database\DatabaseTestCase;
  8. class EloquentTouchParentWithGlobalScopeTest extends DatabaseTestCase
  9. {
  10. protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
  11. {
  12. Schema::create('posts', function (Blueprint $table) {
  13. $table->increments('id');
  14. $table->string('title');
  15. $table->timestamps();
  16. });
  17. Schema::create('comments', function (Blueprint $table) {
  18. $table->increments('id');
  19. $table->integer('post_id');
  20. $table->string('title');
  21. $table->timestamps();
  22. });
  23. }
  24. public function testBasicCreateAndRetrieve()
  25. {
  26. $post = Post::create(['title' => Str::random(), 'updated_at' => '2016-10-10 10:10:10']);
  27. $this->assertSame('2016-10-10', $post->fresh()->updated_at->toDateString());
  28. $post->comments()->create(['title' => Str::random()]);
  29. $this->assertNotSame('2016-10-10', $post->fresh()->updated_at->toDateString());
  30. }
  31. }
  32. class Post extends Model
  33. {
  34. public $table = 'posts';
  35. public $timestamps = true;
  36. protected $guarded = [];
  37. public function comments()
  38. {
  39. return $this->hasMany(Comment::class, 'post_id');
  40. }
  41. public static function boot()
  42. {
  43. parent::boot();
  44. static::addGlobalScope('age', function ($builder) {
  45. $builder->join('comments', 'comments.post_id', '=', 'posts.id');
  46. });
  47. }
  48. }
  49. class Comment extends Model
  50. {
  51. public $table = 'comments';
  52. public $timestamps = true;
  53. protected $guarded = [];
  54. protected $touches = ['post'];
  55. public function post()
  56. {
  57. return $this->belongsTo(Post::class, 'post_id');
  58. }
  59. }