EloquentPushTest.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Support\Facades\Schema;
  6. class EloquentPushTest extends DatabaseTestCase
  7. {
  8. protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
  9. {
  10. Schema::create('users', function (Blueprint $table) {
  11. $table->increments('id');
  12. $table->string('name');
  13. });
  14. Schema::create('posts', function (Blueprint $table) {
  15. $table->increments('id');
  16. $table->string('title');
  17. $table->unsignedInteger('user_id');
  18. });
  19. Schema::create('comments', function (Blueprint $table) {
  20. $table->increments('id');
  21. $table->string('comment');
  22. $table->unsignedInteger('post_id');
  23. });
  24. }
  25. public function testPushMethodSavesTheRelationshipsRecursively()
  26. {
  27. $user = new UserX;
  28. $user->name = 'Test';
  29. $user->save();
  30. $user->posts()->create(['title' => 'Test title']);
  31. $post = PostX::firstOrFail();
  32. $post->comments()->create(['comment' => 'Test comment']);
  33. $user = $user->fresh();
  34. $user->name = 'Test 1';
  35. $user->posts[0]->title = 'Test title 1';
  36. $user->posts[0]->comments[0]->comment = 'Test comment 1';
  37. $user->push();
  38. $this->assertSame(1, UserX::count());
  39. $this->assertSame('Test 1', UserX::firstOrFail()->name);
  40. $this->assertSame(1, PostX::count());
  41. $this->assertSame('Test title 1', PostX::firstOrFail()->title);
  42. $this->assertSame(1, CommentX::count());
  43. $this->assertSame('Test comment 1', CommentX::firstOrFail()->comment);
  44. }
  45. }
  46. class UserX extends Model
  47. {
  48. public $timestamps = false;
  49. protected $guarded = [];
  50. protected $table = 'users';
  51. public function posts()
  52. {
  53. return $this->hasMany(PostX::class, 'user_id');
  54. }
  55. }
  56. class PostX extends Model
  57. {
  58. public $timestamps = false;
  59. protected $guarded = [];
  60. protected $table = 'posts';
  61. public function comments()
  62. {
  63. return $this->hasMany(CommentX::class, 'post_id');
  64. }
  65. }
  66. class CommentX extends Model
  67. {
  68. public $timestamps = false;
  69. protected $guarded = [];
  70. protected $table = 'comments';
  71. }