Home > Mobile >  use relations in controller
use relations in controller

Time:11-20

Hi I want to implement this through relationships that show questions that the user of my site has registered answers and can see the questions in which he participated. I dont know what should I do. this is my controller

public function index(){

   $threads=Thread::with('answers')->where('user_id','=',auth()->user()->id)->get();

   return view('answer-question.thread.thread', compact('threads'));

}

Column user_id is in the answer table and this is my view that i wanna use foreach (show the Threads that have the condition ) and i have one to many relation between Thread and Answer

   @foreach($thread as $thread)
   <dive>..........</dive>
   @endforeach

CodePudding user response:

If i understandood this, do you need something like this:

$threads=Thread::with('answers')->where('answers.user_id','=',auth()->user()->id)->get();

CodePudding user response:

You should do it like this:

$threads=Thread::with(['answers'=>function ($query) {
            $query->where('user_id',auth()->id());
        })
    ])->get();
  • Related