WST87448735
@WST87448735

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

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

1Answer

多分ですが

Answer::with('comments')
↓
Answer::with('comment')

にしたらいける気が。いけなかったらすいません

0Like

Comments

  1. @WST87448735

    Questioner

    @kamotetuさん
    ありがとうございます!
    いけませんでした。Trying to get property 'body' of non-objectと出ます。
  2. 残念です!😭
    というか、これてcommentが親でanswerがその子に当たりますよね?
    whereで('comment_id','=','comments.id')

    $comment = Comment::find($comment_id);
    ...->where('comment_id','=',$comment->id)->get();

    でやったら取れませんか?
  3. @WST87448735

    Questioner

    とれました!ありがとうございます( ノД`)シクシク…
  4. ( ノД`)オォヨクヤッタヨ…

Your answer might help someone💌