I have two collections products
and authors
with a simple many-to-many
relationship. I cannot retrieve from these two collections the data entered as a pivot in the products collection as the example:
ModelProduct.php
class Product extends MongoModel {
protected string $collection = 'products';
public function authors()
{
return $this->belongsToMany(Author::class)->withPivot('role');
}
}
ModelAuthor.php
class Author extends MongoModel {
protected string $collection = 'authors';
public function products()
{
return $this->belongsToMany(Product::class)->withPivot('role');
}
}
JsonData Product
{
"_id": "669eacae26a4b8ef63038f22",
"title": "Helloworld",
"author_ids": [{
"id": "669eacae26a4b8ef63038f23",
"role": "Illustrator"
}]
}
JsonData Author
{
"_id": "669eacae26a4b8ef63038f23",
"firstname": "John",
"lastname": "Doe"
"product_ids": [
"669eacae26a4b8ef63038f22"
]
}
Laravel example for pivot “role” column
foreach ($product->authors as $author) {
dd($author->pivot->role);
}
New contributor
Luca Dario Carità is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.