[英]Get data from relationship, Laravel
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.我有一个使用
with
获取数据的查询,但在该表中我有另一个关系,我想从中获取数据,但我不确定如何获取。
The result that I need is between question_topics
and lk_answers
(there I have the names for topic_1, topic_2 ...)我需要的结果是在
question_topics
和lk_answers
之间(那里我有 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));
}
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:首先在用于
question_topics
的模型上,您需要定义best_match_topic
、 topic_1
、 topic_2
和topic_3
的关系:
eg.例如。
QuestionTopic
class QuestionTopic
类
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();
If I understand your question correctly, you want question_topics data return response in json .如果我正确理解您的问题,您希望 question_topics 数据在 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.这将为您提供一个 Question 数组,每个 Question 对象中都有一个 question_topics 数组。 Loop iteration get like in php
$loop_raw->question_topics->best_match_topic
循环迭代就像在 php
$loop_raw->question_topics->best_match_topic
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.