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

morphToMany Relation does not work

Open ghost opened this issue 3 years ago • 2 comments

@jenssegers @divine

  • Laravel-mongodb Version: 3.9
  • PHP Version: 8.0.1

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"}})

ghost avatar Feb 27 '22 09:02 ghost

+1

HamidVetr avatar Feb 28 '22 08:02 HamidVetr

+1

ali-hbz avatar Feb 28 '22 08:02 ali-hbz