Laravel-mongodb: Laravel 5.5 : MongoDB & hasManyThrough() relation

Created on 27 Sep 2017  路  3Comments  路  Source: jenssegers/laravel-mongodb

I use MongoDB with Laravel: https://github.com/jenssegers/laravel-mongodb

I have two tables (feeds, users) and a collection on MongoDB (articles) that come in this form:

articles (MongoDB):

_id (ObjectID)
feed_id
title
feeds (MySQL):

id
user_id
name
users (MySQL):

id
name

I would like to retrieve all the articles of a user while passing by "feeds".

For this, I use the hasManyThrough() relation in the User model:

public function articles()
    {
        return $this->hasManyThrough(
            Article::class,
            Feed::class,
            'user_id',
            'feed_id',
            '_id',
            'id'
        );
    }

But the problem is that on each user, I have the same articles listed, it looks like it does not take into account user_id...

question

Most helpful comment

Is there an elegant way to perform "hasManyThrough" functionality?

All 3 comments

Hey mate,

Did you see this? https://github.com/jenssegers/laravel-mongodb#relations

Relations

Supported relations are:

    hasOne
    hasMany
    belongsTo
    belongsToMany
    embedsOne
    embedsMany

Is there an elegant way to perform "hasManyThrough" functionality?

Here's an (elegant?) solution to performing a "hasManyThrough" functionality.


public function feeds()
{
   return $this->hasMany('App\Feeds');
}

public function articles()
{
    $feeds_ids = $this->feeds()->select('feeds._id')->get()->pluck('_id');
    return Articles::whereIn('feeds_id', $feeds_ids);
}

Doing this, will give you the same feel as using a hasManyThrough relationship.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

naveedyasin picture naveedyasin  路  3Comments

YSimple picture YSimple  路  3Comments

bastiendonjon picture bastiendonjon  路  3Comments

tomartailored picture tomartailored  路  3Comments

HassanIbrahim picture HassanIbrahim  路  3Comments