Laravel + Jenssegers\Mongodb: 'WhereHas' and 'Has' returns empty collection

余生颓废 提交于 2019-12-22 08:06:24

问题


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?

来源:https://stackoverflow.com/questions/42430157/laravel-jenssegers-mongodb-wherehas-and-has-returns-empty-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!