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.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community