Laravel MongoDB 无法正确获取belongsTo 关系值

问题描述

当使用 jenssegers/laravel-mongodb 时,belongsTo 关系总是正确地返回 null,尽管在转储时会出现该值。我如何获得belongsTo 关系?

我有两个模型,一个帖子和一个用户。帖子与用户有属于关系的地方。当我使用 $post->user 时,我总是得到 null。尽管在转储 ($post) 时它清楚地显示用户 ID!

用户(使用样板 Laravel 身份验证,MongoDB 身份验证用户除外)

use Jenssegers\Mongodb\Auth\User as Authenticatable;
class User extends Authenticatable
{
    use HasFactory,Notifiable;

    protected $collection = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name','email','password',];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password','remember_token',];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',];
}

发布:

use Jenssegers\Mongodb\Eloquent\Model;

class Post extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

根据 Jessenger 的自述文件,这是相当标准的,没什么特别的。

Post::all()->first() related values dump
  #attributes
    "_id" => MongoDB\BSON\ObjectId {#1601 ▶}
    "user" => "602f054f6294a33233745fab"

我使用这个保存了用户,只是获取登录用户的 ID。

$post->user = auth()->user()->getAuthIdentifier();

然而,获取 $post->user 总是返回 null

$post = Post::all();
dd($post->user) // null

$post->user() 工作并返回关系,相关值是实际用户

其他帖子建议设置外键和本地键

帖子类

public function user()
{
   return $this->belongsTo(User::class,'user_id','_id');
}

这也不起作用。

最初我将用户保存为 ObjectId,但这也不起作用。

我目前的想法是完全废弃belongsTo函数并手动设置相关ID。问题是现在我需要手动查询用户而不是包为我这样做,或者使用 Post::with('user') 自动加载它。

如何获取belongsTo 关系ID 值?

  • PHP:8.0.2
  • Laravel 框架:8.28.1
  • 杰森格斯/MongoDB:3.8.2

解决方法

我发现了一个奇怪的解决方法,将 user_id 添加到可填写字段并填写

use Jenssegers\Mongodb\Eloquent\Model;

class Post extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name','user_id'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

EG 控制器

$post->user_id = $userID;

然后查询用户工作正常

$post = Post::all();
dd($post->user); // Gets the user,no longer null
dd($post->user_id); // This is the user id field you filled out before. Returns the user id

为什么这会起作用超出了我微不足道的凡人头脑的理解范围。有趣的是不需要设置 $post->user。