Reputation: 1513
I have a query where I get data using with
, but in that table I have another relationship and I want to get data from that, and I am not sure how.
The result that I need is between question_topics
and lk_answers
(there I have the names for topic_1, topic_2 ...)
public function index(Request $request)
{
$query = Question::select(['id', 'free_text', 'title', 'topics_id', 'created_at']);
$query->with('question_topics');
$query->question_topics->with('lkp_answers'); // something like that, but this line is not working.
return response()->json($query->paginate(5));
}
Upvotes: 2
Views: 116
Reputation: 606
First
On the model that is used for question_topics
, you need to have the relationships for best_match_topic
, topic_1
, topic_2
, and topic_3
defined:
eg. QuestionTopic
class
class QuestionTopic {
public function bestMatchTopic() {
return $this->belongsTo(Topic::class, 'best_match_topic');
}
public function topicOne() {
return $this->belongsTo(Topic::class, 'topic_1');
}
public function topicTwo() {
return $this->belongsTo(Topic::class, 'topic_2');
}
public function topicThree() {
return $this->belongsTo(Topic::class, 'topic_3');
}
}
Then, if you want to get the relationship of a relationship, you can access them using the dot notation:
Question::with('question_topics.bestMatchTopic',
'question_topics.topicOne',
'question_topics.topicTwo',
'question_topics.topicThree')->get();
Upvotes: 1
Reputation: 711
If I understand your question correctly, you want question_topics data return response in json .
public function index(Request $request)
{
$query = Question::select(['id', 'free_text', 'title', 'topics_id', 'created_at']);
$query->with('question_topics');
return response()->json($query->paginate(5));
}
This will give you an array of Question that have a question_topics array in each Question object. Loop iteration get like in php $loop_raw->question_topics->best_match_topic
Upvotes: 0