Bogdan  Dubyk
Bogdan Dubyk

Reputation: 5530

Eloquent model setRelation generating array instead of Collection

If you are doing $instance = $model->with('categories')->find($id); and after var_dump($instance->categories) it going to return Collection of categories.

But on the project I'm working on in some heavy queries, we are not using with and getting data with a combination of GROUP_CONCAT and CONCAT, like this: \DB::raw('GROUP_CONCAT(DISTINCT CONCAT(categories.id, ",,", categories.name) SEPARATOR ";;") as categories'), And then we are building relations manually parsing result and creating a relationship using $instance->setRelation($relation, $data) but for some reason, it's returning an array of objects instead of Collection.

There are also option to use setRelations() and this method returning Collection but I found if you have bidirectional relations it's creating recursion and working really slow. For example: if in User model we have set $this->hasMany('Comments') and in Comments model we have set return $this->belongsTo('User'); and after when we running setRelations() to manually build relations it is create nesting models with recursion (User->Comments->User and so on).

The third option is to not use setRelation() or setRelations() and just to manually create Collection, populating it and set to model. But in such case, it will not be set as a model relation.

Any suggestions on how to build manually in the right way (to create relation is same way eloquent creating with with).

Upvotes: 0

Views: 9234

Answers (1)

rkj
rkj

Reputation: 8287

Group return collection of collection so you have to remove the keys of first collection and for that you can use values function of collection like this

$instance->setRelation('relation', $data->values()->all());

Details https://laravel.com/docs/5.6/collections#method-values

Upvotes: 3

Related Questions