*前提、実現したいこと
現在、laravelでメルカリのクローンアプリを製作しています。
実現したいことは閲覧者からの質問に対して出品者がした解答を閲覧者サイドから見れるようにすることです。
productテーブル(商品)
・id
userテーブル
・id
commnetテーブル(質問)
・porduct_id
・user_id
・body
answerテーブル(解答)
・comment_id
・user_id
・body
この四つのテーブルがあります。
userは複数のproductを持ち、またproductは複数のcommentを持てます。
commentは一つのanswerしか持つことができません。
*つまづいていること
bladeで出品者からの解答を表示させようとする時
php
1ErrorException (E_ERROR) 2Property [answer] does not exist on this collection instance.
このようなエラーが出てきます。
*該当するコード
Controller.php
php
1public function list(Request $request) 2 { 3 $product = Product::find($request->id); 4 $comment = Comment::where('product_id', $request->id) 5 ->where('user_id', Auth::user()->id) 6 ->get(); 7 8 9 10 return view('admin.mercari.list', ['product' => $product, 'comment' => $comment]); 11 }
blade.php
php
1<div class="row"> 2 <div class="col-md-10"> 3 @if($comment->answer->count() == 0) 4 <div class="title"> 5 <h4>出品者からの返信はまだありません</h4> 6 </div> 7 @else 8 <div class="title"> 9 <h4>出品者からの返信</h4> 10 </div> 11 <div class="time"> 12 {{ "返信日時:".$comment->answer->created_at }} 13 </div> 14 <div class="body"> 15 {{ "本文:".$comment->answer->body }} 16 </div> 17 @endif 18 </div> 19 </div>
comment.php
php
1public function answer() 2 { 3 return $this->hasOne('App\Answer'); 4 }
answer.php
php
1class Answer extends Model 2{ 3 protected $guarded = array('id'); 4 5 public static $rules = array( 6 'body' => 'required', 7 ); 8 9 public function user() 10 { 11 return $this->belongsTo('App\User'); 12 } 13 14 public function comment() 15 { 16 return $this->belongsTo('App\Comment'); 17 } 18 19 public function product() 20 { 21 return $this->belongsTo('App\Answer'); 22 } 23}
また、dd($commnet)してみたところ
php
1Collection {#266 ▼ 2 #items: array:1 [▶] 3}
と表示されました。
以上です。
よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。