laravel-mongodb icon indicating copy to clipboard operation
laravel-mongodb copied to clipboard

jenssegers/mongodb Unable to write accessor or use alias for nested column

Open ahmed130544 opened this issue 3 years ago • 0 comments

I am working with Laravel, where used package jenssegers/mongodb, Want to return nested column as a specific key like "review_title", but unable to use alias or write accessor, group by worked by it creates some issues as well.

Following is my code

`public function getTopicsWithPagination($namespaceId, $asofdate, $algorithm, $skip, $pageSize, $nickNameIds, $search = '') { try { $nextDay = $asofdate + 86400; $record = $this->treeModel::where('algorithm_id', $algorithm) ->where('as_of_date', '>=', $asofdate) ->where('as_of_date', '<', $nextDay);

        $record->when($namespaceId !== '', function ($q) use($namespaceId) { 
            $q->where('namespace_id', $namespaceId);
        });

        $record->when(!empty($nickNameIds), function ($q) use($nickNameIds) { 
            $q->whereIn('submitter_nick_id', $nickNameIds);
        });
        
        if (isset($search) && $search != '') {
            $record = $record->where('topic_name', 'like', '%' . $search . '%');
        };

        $record = $record->project(['_id' => 0])
            ->skip($skip)
            ->take($pageSize)
            ->orderBy('topic_score', 'desc')
            ->groupBy('topic_name')
            ->get(['topic_id', 'topic_score', 'topic_name', 'as_of_date', 'tree_structure.1.review_title']);
        return $record;
    } catch (\Throwable $th) {
        return $th->getMessage();
    }
}`

And Tree model code is: `use Jenssegers\Mongodb\Eloquent\Model;

class Tree extends Model { protected $connection = 'mongodb'; protected $collection = 'trees'; protected $guarded = []; }`

Following is the response: { "status_code": 200, "message": "Success", "error": null, "data": { "topic": [ { "topic_id": 88, "as_of_date": 1655769600, "topic_name": "Theories of Consciousness", "tree_structure": { "1": { "review_title": "Theories of Consciousness" } }, "topic_score": 63.49 } ], "number_of_pages": 357 } }

but want to have following one where alias nested column of review_title { "status_code": 200, "message": "Success", "error": null, "data": { "topic": [ { "topic_name": "Theories of Consciousness", "topic_id": 88, "topic_score": 63.49, "as_of_date": 1655769600, "tree_structure_1_review_title": "Theories of Consciousness" } ], "number_of_pages": 357 } }

ahmed130544 avatar Jun 22 '22 08:06 ahmed130544