Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

afoysal's avatar

Get Join query result in different JSON Object Key

I have a Query like below in my Laravel controller which one I am using for API development.

    return $post
                ->comments()
                ->join('translationCHN', function ($join) {
                    $join->on('comment.word_id', '=', 'translationCHN.word_id');
                    $join->on('comment.sentence_id', '=', 'translationCHN.sentence_id');
                })
                ->get();

I am getting output in JSON format. From this query I would like to get result in different JSON Object Key translationCHN.

How can do that ?

0 likes
3 replies
Tray2's avatar

If I understand your question correctly you want to rename one of the result columns to something else?

In SQL you can do that quite easily SELECT column as column_alias FROM table: Not an master of Eloquent but there should be something similar to give the column an alias.

1 like
afoysal's avatar

Thanks @Tray2 . I know raw SQL but I am looking for Eloquent solution. Thanks.

pinakmithaiwala's avatar

On You Controller ->comments() ->with('translationCHN'); ->get();

On You Model

public function translationCHN()
{
    return $this->belongsTo('App\Models\Comments','word_id','word_id')
                 ->where('comment.sentence_id',$this->sentence_id);
}
1 like

Please or to participate in this conversation.