从关系中获取数据,Laravel

Get data from relationship, Laravel

我有一个查询,我使用 with 获取数据,但在那 table 我有另一个关系,我想从中获取数据,但我不确定如何。

我需要的结果在 question_topicslk_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));
}

如果我对你的问题的理解正确,你需要 question_topics 数据 return 在 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));
}

这将为您提供一个问题数组,每个问题对象中都有一个 question_topics 数组。循环迭代就像 php $loop_raw->question_topics->best_match_topic

第一个 在用于 question_topics 的模型上,您需要定义 best_match_topictopic_1topic_2topic_3 的关系:

例如。 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');
    }

}

然后,如果你想获取关系的关系,你可以使用点符号访问它们:

Question::with('question_topics.bestMatchTopic', 
                   'question_topics.topicOne', 
                   'question_topics.topicTwo', 
                   'question_topics.topicThree')->get();