mongodb / laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)
https://www.mongodb.com/docs/drivers/php/laravel-mongodb/
MIT License
7.02k stars 1.43k forks source link

morphToMany Relation does not work #2360

Open ghost opened 2 years ago

ghost commented 2 years ago

@jenssegers @divine

Description:

Steps to reproduce

Post Model :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Jenssegers\Mongodb\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $guarded = [];
    protected $connection = 'mongodb';

    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
}

posts collection :

{
    _id: ObjectId('621b30473a86531fe1361a13'),
    name: 'first post',
    updated_at: ISODate('2022-02-27T08:03:19.527Z'),
    created_at: ISODate('2022-02-27T08:03:19.527Z')
}

Tag Model :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Jenssegers\Mongodb\Eloquent\Model;

class Tag extends Model
{
    use HasFactory;

    protected $connection = 'mongodb';
    protected $guarded = [];

    public function posts()
    {
        return $this->morphedByMany(Post::class, 'taggable');
    }
}

tags collection :

{
    _id: ObjectId('621b30473a86531fe1361a12'),
    name: 'first tag',
    updated_at: ISODate('2022-02-27T08:03:19.507Z'),
    created_at: ISODate('2022-02-27T08:03:19.507Z')
}

taggables collection :

{
    _id: ObjectId('621b30473a86531fe1361a14'),
    tag_id: '621b30473a86531fe1361a12',
    taggable_id: '621b30473a86531fe1361a13',
    taggable_type: 'App\\Models\\Post'
}

query :

         Post::query()->with('tags')->get();

result :

[
{
"_id": "621b30473a86531fe1361a13",
"name": "first post",
"updated_at": "2022-02-27T08:03:19.527000Z",
"created_at": "2022-02-27T08:03:19.527000Z",
"tags": []
}
]

query show in laravel debugbar

posts.find([],{"typeMap":{"root":"array","document":"array"}})
tags.find({"$and":[{"taggables.taggable_id":{"$in":["621b30473a86531fe1361a13"]}},{"taggables.taggable_type":"App\\Models\\Post"}]},{"projection":{"tags.*":true,"taggables.taggable_id as pivot_taggable_id":true,"taggables.tag_id as pivot_tag_id":true,"taggables.taggable_type as pivot_taggable_type":true},"typeMap":{"root":"array","document":"array"}})
HamidVetr commented 2 years ago

+1

ali-hbz commented 2 years ago

+1