Funtriaco Prado Funtriaco Prado - 1 month ago 7
PHP Question

Laravel MongoDB hasMany relationship is not working

I'm try to create a relationship between albums and photos (an Album has many photos). Below is my controller and what my models look like. Interesting enough, the reverse relationship photo->album (belongsTo) works fine! but the album->photos returns an empty collection.

## The hasMany relationship does NOT work... I get an empty collection
<?php
class AlbumController extends BaseController
{
public function show(Request $request, $album_id)
{
$album = Album::find($album_id);
dd($album->photos);
}
}

## Results:
# Collection {#418
# items: []
# }


## The belgonsTo relationship works
<?php
class PhotoController extends BaseController
{
public function show(Request $request, $photo_id)
{
$photo = Photo::find($photo_id);
dd($photo->album);
}
}

<?php

namespace App;

use DB;
use Jenssegers\Mongodb\Eloquent\SoftDeletes;
use Moloquent;

class Album extends Moloquent
{
use RecordActivity, SoftDeletes;

protected $connection = 'mongodb';
protected $table = 'albums';
protected $collection = 'albums';
protected $primaryKey = "_id";
protected $dates = ['deleted_at'];
protected $fillable = ['user_id','name','is_private'];

public function photos()
{
// Neither seems to work
//return $this->embedsMany('Photo');
return $this->hasMany('App\Photo');
}
}

<?php

namespace App;

use DB;
use Jenssegers\Mongodb\Eloquent\SoftDeletes;
use Moloquent;

class Photo extends Moloquent
{
use RecordActivity, SoftDeletes;

protected $connection = 'mongodb';
protected $table = 'photos';
protected $collection = 'photos';
protected $primaryKey = "_id";
protected $dates = ['deleted_at'];
protected $fillable = ['album_id', 'user_id', 'name', 'folder', 'is_private', 'caption'];
protected $hidden = [];

// user and album belongsTo works
public function user()
{
return $this->belongsTo('App\User');
}

public function album()
{
return $this->belongsTo('App\Album');
}
}

Answer

The issue had to do with the fact that my IDs were ObjectID and it seems to be an issue with Jessengers Laravel MongoDB Drivers... we have actually decided to move back to MariaDB to fully utilize Eloquent/Relationships

Comments