简体   繁体   中英

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.

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));
}

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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