Support the ongoing development of Laravel.io →
Database Eloquent

I'm using the Laravel-MongoDb package with a many to many relationship between "expeditions" and "subjects". Expeditions is MySql, Subjects is MongoDb. There is a pivot table "expedition_subject" that exists on one side, and within the Subjects collection, the Expedition Ids are stored in a "expedition_ids" field as an array.

"expedition_ids": [
     "1", "2", "3" 
  ] 

I'm trying to get the count for Subjects that are associated with an Expedition. For example:

$project = $this->project->findWith($id, ['expeditions.subjectsCountRelation']);

Projects have one to many relationship with Expeditions. Inside the Expedition Model, I have this:

        /**
	 * Return count through relationship
	 * @return mixed
	 */
	public function subjectsCountRelation ()
	{
		return $this->belongsToMany('Subject')
                            ->selectRaw('expedition_ids, count(*) as count')
                            ->groupBy('expedition_ids');
	}

	/**
	 * Get counts attribute
	 *
	 * @return int
	 */
	public function getSubjectsCountAttribute ()
	{
		return $this->subjectsCountRelation->first() ? 
                               $this->subjectsCountRelation->first()->count : 0;
	} 

Obviously it's not working due to the raw query being wrong. No error is generated. It simply returns nothing. Any ideas on how I might accomplish this?

Oh.... the above generates this MongoDB query

subjects.aggregate([
    {
        "$match": { "expedition_ids":  {  "$in":["1","2","3"] } }
    },
    {
         "$group":
         {
              "_id": { "expedition_ids":"$expedition_ids" },
              "expedition_ids": { "$last":"$expedition_ids" },
              "count(expedition_ids) as count(*)": { "$last":"$count(expedition_ids) as count(*)" }
        }
   }
])

I know the 3 Expeditions I have include 100 Subjects in each from the database seeding.

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

rbruhn rbruhn Joined 16 Apr 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.