我试图在相册和照片之间建立一种关系(相册有很多照片)。下面是我的控制器和我的模型的样子。有趣的是,反向关系照片->相册(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');
}
}发布于 2016-06-17 14:14:46
这个问题与我的身份证是ObjectID有关,这似乎是耶森格斯拉勒维尔MongoDB司机的问题.我们实际上已经决定回到MariaDB,充分利用雄辩的/关系
发布于 2016-10-19 23:05:12
我做了和你一样的事情,我发现Mongodb没有什么问题。因为Mongodb将"_id“定义为主键,这就是它无法获得正确关系的原因: belongsTo和hasMany。因此,我在父模型的顶部声明了$primaryKey = "id“,做了一个小小的修改,它运行得很好
发布于 2022-08-01 18:54:08
这对我有用。
/**
* @return HasMany
*/
public function tasks(): HasMany
{
return $this->hasMany(ProjectTask::class, 'project_id', 'idAsString');
}https://stackoverflow.com/questions/37423816
复制相似问题