2

I'm working with a Mongo database, and i have a Reading List with a BelongsToMany Relationship to a Stories table, it seems like this:

public function stories()
{
    return $this->belongsToMany(Story::class, null);
}

Then, on the controller, i want to return a list of them, which contains only the id and title of the story list, i searched, and found many ways, but all them caused the same error, this is one of them:

$user = auth()->user();

$readingList = ReadingList::where('user_id', $user->id)->with(["stories"=> function ($query) {

    $query->select("title");

}])->paginate(10);

And causes: Invalid argument supplied for foreach().

I took out the filter to verify it works, and answered correctly.

[
    {
        "_id": "6148dc2a23ef6d0e6838h123",
        "name": "MyReadingList",
        "stories": [
            {
                "_id": "611a64f5f735f32dcc5ab657",
                "title": "Lorem",
                "blurb": "Ipsum"
            }
        ]
    }
]

Am i doing this wrong, or how do you filter the fields with Jensseger library and BelongsToMany?

UPDATE

After a little debugging, seems like i found the cause, but i'm not sure how to solve it, in the Jensseger BelongsToMany file, there is a function like this:

protected function buildDictionary(Collection $results)
{
    $foreign = $this->foreignPivotKey;

    // First we will build a dictionary of child models keyed by the foreign key
    // of the relation so that we will easily and quickly match them to their
    // parents without having a possibly slow inner loops for every models.
    $dictionary = [];

    foreach ($results as $result) {
        foreach ($result->$foreign as $item) {
            $dictionary[$item][] = $result;
        }
    }

    return $dictionary;
}

Here, $result is equal to {"_id":"6148dc2a23ef6d0e6838h123"}, which is my filtered result, but then it tries to access $result->$foreign, where $foreign is 'reading_list_ids', the pivot column, but is not here, hence returning a null and launching that error.

I tried adding reading_list_ids(And removing it from hidden) like $readingList = ReadingList::where('user_id', $user->id)->with("stories:title,reading_list_ids")->get();, still didn't work. Interestingly, i tried testing this without the filter, but with reading_list_ids hidden, it showed something like this {"_id":"6148dc2a23ef6d0e6838h123","title":"Lorem","blurb":"Ipsum","completed":"1"}, still not that field there, but it doesn't launch that error and works.

Does anyone knows how to bypass this, or make it work?

Efraín
  • 453
  • 1
  • 7
  • 13

0 Answers0