Laravel 質問と回答の実装
解決したいこと
コメントに紐づけた回答の表示
Laravel6において、レシピアプリを作成中です。
コメントに対しての答え(Answer)を表示させたいです。
よろしくお願いいたします。
RecipeController.php
public function show($id)
{
$recipe = Recipe::find($id);
$user = \Auth::user();
$answers = Answer::with('comments')->where('comment_id','=','comments.id')->get();
dd($answers);
return view('recipes.show',[
'title' => 'レシピ詳細',
'recipe' => $recipe,
'user' => $user,
'answers' => $answers,
]);
}
recipes/show.blade.php
<dd class="accordion-body">
@forelse($answers as $answer)
<div class="accordion-text">{{ $answer->body }}</div>
@empty
<p>回答はありません。</p>
@endforelse
</dd>
Answer.php
use Illuminate\Database\Eloquent\Model;
class Answer extends Model
{
protected $fillable = [
'comment_id','body','user_id','recipe_id'
];
public function comment()
{
return $this->belongsTo('App\Comment');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
Comment.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $fillable = ['recipe_id','user_id','body'];
public function user()
{
return $this->belongsTo('App\User');
}
public function answer()
{
return $this->hasOne('App\Answer');
}
}
自分で試したこと
RecipeController.php
$answers = Answer::with('comments')->where('comment_id','=','comments.id')->get();
dd($answers);
にてanswersテーブルにあるcomment_idとcommentsテーブルにあるidが一致したAnswerを取得しているつもりです。。。
0 likes