【发布时间】:2016-10-20 07:05:12
【问题描述】:
我正在尝试在相册和照片之间建立关系(一个相册有很多照片)。下面是我的控制器和我的模型的样子。有趣的是,反向关系 photo->album (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');
}
}
【问题讨论】:
-
我知道这不是您问题的直接答案,但您不认为您的关系应该是多对多吗?一个相册可以有很多张照片,但另一个相册也可以有相同的照片,对吧?
-
你使用哪个版本的 jenssegers/mongodb?还有哪个版本的mongodb?
-
您也可以尝试打印查询。示例:DB::connection()->enableQueryLog(); $照片 = $相册->照片; dd(DB::getQueryLog());
-
@PiKos jenssegers 版本是 "jenssegers/mongodb": "3.0.1" 及其 MongoDB 3.2
-
@PiKos QueryLog dd:
array:2 [ 0 => array:2 [ "query" => "albums.find({"$and":[{"deleted_at":null},{"_id":{}}]},{"limit":1,"typeMap":{"root":"array","document":"array"}})" "bindings" => [] "time" => 12.44 ] 1 => array:2 [ "query" => "photos.find({"$and":[{"deleted_at":null},{"album_id":"5743206f9a89201a011f33d5"},{"album_id":{"$ne":null}}]},{"typeMap":{"root":"array","document":"array"}})" "bindings" => [] "time" => 14.59 ] ]
标签: php mongodb laravel eloquent