前提
PHP/Laravel でツイッターのようなwebサイトを作りたいと考えています。
実現したいこと
- リツイート機能の追加
発生している問題・エラーメッセージ
・$fire->retweeted()を指定してもリツイート投稿が出てこない
該当のソースコード
PHP/Laravel
1モデルファイル 2<Fire.php> 3/** 4 * あるリツイート投稿自体を指す 5 */ 6 public function retweeted() 7 { 8 $this->hasMany(Retweet::class, 'retweeted_id', 'id'); 9 } 10 11 /** 12 * あるリツイート投稿の引用元を指す 13 */ 14 public function retweeting() 15 { 16 $this->hasOne(Retweet::class, 'retweeting_id', 'id'); 17 } 18 19マイグレーションファイル 20(retweets) 21public function up() 22 { 23 Schema::create('retweets', function (Blueprint $table) { 24 $table->bigIncrements('id'); 25 $table->unsignedBigInteger('retweeted_id'); 26 $table->foreign('retweeted_id')->references('id')->on('fires')->onDelete('cascade'); 27 $table->unsignedBigInteger('retweeting_id'); 28 $table->foreign('retweeting_id')->references('id')->on('fires')->onDelete('cascade'); 29 $table->timestamps(); 30 31 //この後追加 32 $table->unsignedBigInteger('retweeting_id')->nullable()->change(); 33 }); 34 } 35(fires) 36 Schema::create('fires', function (Blueprint $table) { 37 $table->bigIncrements('id'); 38 $table->unsignedBigInteger('user_id'); 39 $table->string('content'); 40 $table->timestamps(); 41 42 // 外部キー制約 43 $table->foreign('user_id')->references('id')->on('users'); 44 }); 45 46MySQL 47firesテーブル 48----+---------+---------+---------------------+---------------------+ 49| id | user_id | content | created_at | updated_at | 50+----+---------+---------+---------------------+---------------------+ 51| 74 | 1 | 1 | 2022-08-09 17:37:02 | 2022-08-09 17:37:02 | 52| 86 | 1 | 2 | 2022-08-10 13:48:41 | 2022-08-10 13:48:41 | 53| 87 | 1 | 2 | 2022-08-10 13:48:42 | 2022-08-10 13:48:42 | 54+----+---------+---------+---------------------+---------------------+ 55retweetsテーブル 56+----+--------------+---------------+---------------------+---------------------+ 57| id | retweeted_id | retweeting_id | created_at | updated_at | 58+----+--------------+---------------+---------------------+---------------------+ 59| 18 | 86 | 87 | 2022-08-10 13:48:42 | 2022-08-10 13:48:42 | 60+----+--------------+---------------+---------------------+---------------------+ 61 62>>> $fire = Fire::find(86); 63=> App\Fire {#4290 64 id: 86, 65 user_id: 1, 66 content: "2", 67 created_at: "2022-08-10 13:48:41", 68 updated_at: "2022-08-10 13:48:41", 69 } 70>>> $fire->hasMany(Retweet::class, 'retweeted_id', 'id')->get(); 71=> Illuminate\Database\Eloquent\Collection {#4286 72 all: [ 73 App\Retweet {#4306 74 id: 18, 75 retweeted_id: 86, 76 retweeting_id: 87, 77 created_at: "2022-08-10 13:48:42", 78 updated_at: "2022-08-10 13:48:42", 79 }, 80 ], 81 } 82>>> $fire->retweeted(); 83=> null
試したこと
tinker で $fire = Fire::first(); として、その投稿をリツイートした。そしてリツイートテーブルにもきちんとデータが入っていた。しかしtinkerで$fire->retweeted()としてもnullが帰ってきてしまう。なぜか$fire->hasMany(Retweet::class, 'retweeted_id', 'id')ならきちんと狙い通りの結果が帰ってきた。
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。
回答1件
あなたの回答
tips
プレビュー