mercredi 12 décembre 2018

Undefined property: App\User::$login using Jenssegers\Mongodb

I am having troubles to relate two classes using Laravel 5.5 and Jenssegers\Mongodb.

Here is my User class:

<?php
namespace App;

use App\Login;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class Usuario extends Eloquent
{
    protected $connection = 'mongodb';
    protected $collection = 'user';

    protected $fillable = [
        'name', 'nickname', 'date_birth', 'gender', 'login',
    ];

     public function login(){
        return $this->belongsTo(Login::class, 'login');
    }

}

And here is my Login class:

<?php
namespace App;

use App\User;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class Login extends Eloquent
{
    protected $connection = 'mongodb';
    protected $collection = 'login';

    protected $fillable = [
        'email', 'password',
    ];

    protected $hidden = [
        'password',
    ];

    public function user(){
        return $this->hasOne(User::class, 'login');
    }   
}

On UserController, I defined index method like this:

public function index()
{
    try {

    $user= User::with('login')->get();

    return response()->json(['users' => $user], 200);

    } catch(Exception $e) {
       throw new Exception($e);
    }
}

When I POST an user with a login to store method, it works well. However, when I call GET, I get this message:

ErrorException (E_NOTICE) Undefined property: App\User::$login

On laravel.log, it has:

[2018-12-12 13:05:42] local.ERROR: Undefined property: App\User::$login {"exception":"[object] (ErrorException(code: 0): Undefined property: App\User::$login at [project-path]\vendor\jenssegers\mongodb\src\Jenssegers\Mongodb\Relations\BelongsTo.php:28) [stacktrace]

I already tried to put

use Jenssegers\Mongodb\Relations\BelongsTo;
use Jenssegers\Mongodb\Relations\HasOne;
use Jenssegers\Mongodb\Relations\HasMany;

on the top of each class, however it doesnt work either.

When I call User::all(); on controller, I get the users with the id of login object:

{
   "users": [
              {
                 "_id": "5c10ed8bc557ab2ed0007034",
                 "name": "test user",
                 "login": "5c10ed8bc557ab2ed0007033",
                 //other fields
              }
           ]
}

But I want to get it like this:

{
   "users": [
              {
                 "_id": "5c10ed8bc557ab2ed0007034",
                 "name": "test user",
                 "login": {
                              "_id": "5c10ed8bc557ab2ed0007033",
                              "email": "some@email",
                              "password": "somepwd"
                          },
                 //other fields
              }
           ]
}

I think it's a problem with Jenssegers\Mongodb, because I used this project on a MySQL database and now I am migrating it to MongoDB



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire