5

I'm mainly working on two models right now, Form and Notification, and a many-to-many relationship is set up and working for most Eloquent commands, except for whereHas and has. Both just return an empty array, [].

It seems like the developer has had trouble with getting this to work in the past, but seems to have solved it here.

Here's a sample of what I have so far, and what I've tried:

Form.php

class Form extends Eloquent {
    protected $connection = 'mongodb';

    public function notifications(){
        return $this->belongsToMany('App\Api\Forms\Notification', null, 'form_ids', 'notification_ids');
    }

}

Notification.php

class Notification extends Eloquent {
    protected $connection = 'mongodb';

    public function forms()
    {
        return $this->belongsToMany('App\Api\Forms\Form', null, 'notification_ids', 'form_ids');
    }    
}

NotificationController.php

<?php

namespace App\Http\Controllers;
use App\Api\Forms\Notification;
use App\Api\Forms\Form;

class NotificationController extends Controller
{

    public function getByFormTitle($form_title)
    {
        // This code retuns the relationship as expected.
        // Any forms that are assigned to it are returned.
        // $n = Notification::first();
        // $n->forms()->get();

        // This also returns the relationship correctly, same as before.
        // $f = Form::first();
        // $f->notifications()->get();


        // Nearly identical to the Laravel docs. This returns an empty array, []
        $notifications = Notification::whereHas('forms', function ($query) use ($form_title) {
            $query->where('form_title', $form_title);
        })->get();

        return $notifications;
    }

}

I get the same result if I use Notification::has('form')->get().

So my question is:

Is it possible to use whereHas and has in Jenssegers\Mongodb Eloquent? Do I have to use different syntax than the official Laravel documentation for it, or do I have to make a raw Mongo query for this?

Hollings
  • 534
  • 5
  • 14
  • Did you ever solve this? `whereHas` and `has` return `[]` for me also. `with` works: `Model::with(["items" => function($query) { $query->whereIn("id", [1,2]);}])`, (but I get all `Models`, but only `items` that I specified(e.g. with ids 1 and 2)), so I presume my relations are set properly. (tho I'm using `hasMany` relation) – Traxo Nov 08 '17 at 13:38

0 Answers0