Laravel MongoDB有很多关系不起作用

时间:2016-05-24 21:01:29

标签: php mongodb laravel eloquent

我尝试在相册和照片之间创建关系(相册中有很多照片)。下面是我的控制器以及我的模型。有趣的是,反向关系photo->专辑(belongsTo)工作正常!但是相册 - >照片会返回一个空集合。

## 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');
    }
}

2 个答案:

答案 0 :(得分:0)

问题与我的ID是ObjectID这一事实有关,而且似乎是Jessengers Laravel MongoDB驱动程序的问题......我们实际上决定回到MariaDB以充分利用Eloquent / Relationships

答案 1 :(得分:0)

我做了与你相同的事情,我发现Mongodb没有任何问题。因为Mongodb定义了&#34; _id&#34;作为主键,这是它无法获得正确关系的原因:belongsTo和hasMany。所以我通过声明$ primaryKey =&#34; id&#34;做了一个小改动。在父模型的顶部,它工作正常