簡體   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