繁体   English   中英

从关系中获取数据,Laravel

[英]Get data from relationship, Laravel

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

我需要的结果是在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的模型上,您需要定义best_match_topictopic_1topic_2topic_3的关系:

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

}

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

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

如果我正确理解您的问题,您希望 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));
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM