5

我现在主要在两个模型上工作,Formand Notification,并且为大多数 Eloquent 命令建立了多对多关系,除了whereHasand has。两者都只返回一个空数组,[].

似乎开发人员在过去很难解决这个问题,但似乎在这里解决了。

这是我到目前为止的示例,以及我尝试过的示例:

表单.php

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

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

}

通知.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;
    }

}

如果我使用Notification::has('form')->get().

所以我的问题是:

是否可以使用whereHasand hasin Jenssegers\Mongodb Eloquent?我是否必须使用与官方 Laravel 文档不同的语法,或者我必须为此进行原始 Mongo 查询?

4

0 回答 0