Laravel jenssegers/laravel-mongodb belongsTo混合关联调用报错排查
问题背景
跨SQL、MongoDB双存储创建Eloquent关联时,两个模型代码如下:
SQL端 Location 模型
<?php namespace App\Models\Trend; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Jenssegers\Mongodb\Eloquent\HybridRelations; class Location extends Model { use HasFactory, HybridRelations; protected $table = 'trends'; protected $fillable = [ 'woeid', 'name', ]; public function trends() { return $this->hasMany(Trend::class); } }
MongoDB端 Trend 模型
<?php namespace App\Models\Trend; use App\Models\Scopes\AscendingOrderScope; use App\Models\Team; use App\Models\User; use Illuminate\Database\Eloquent\Factories\HasFactory; use Jenssegers\Mongodb\Eloquent\Model; class Trend extends Model { use HasFactory; protected $connection = 'mongodb'; protected $collection = 'trends'; protected $fillable = ['trends']; protected static function booted() { static::addGlobalScope(new AscendingOrderScope); } public function location() { return $this->belongsTo(Location::class); } }
报错信息
调用Trend模型的->location关联时抛出错误:
PHP Error: Call to a member function prepare() on null in /home/fmk/Code/socmint/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 413
已确认的前置状态:
- MongoDB集合中
location_id字段值对应存在的Location记录ID - 已按文档在Location模型中引入
HybridRelationstrait - 反向关联
location->trends可正常运行
问题根因
HybridRelations trait 必须在关联两端的模型中同时引入,不能仅在SQL端模型使用。
该扩展的混合关联逻辑需要两端模型都加载trait,才能正确识别跨库连接配置。缺少trait时,MongoDB模型执行belongsTo查询会错误调用Mongo连接不存在的SQLprepare方法,触发报错。
修复方法
在Trend模型中引入并使用HybridRelations trait:
<?php namespace App\Models\Trend; use App\Models\Scopes\AscendingOrderScope; use App\Models\Team; use App\Models\User; use Illuminate\Database\Eloquent\Factories\HasFactory; use Jenssegers\Mongodb\Eloquent\Model; use Jenssegers\Mongodb\Eloquent\HybridRelations; class Trend extends Model { use HasFactory, HybridRelations; protected $connection = 'mongodb'; protected $collection = 'trends'; protected $fillable = ['trends']; protected static function booted() { static::addGlobalScope(new AscendingOrderScope); } public function location() { return $this->belongsTo(Location::class); } }
修改后关联即可正常运行。
内容的提问来源于stack exchange,提问作者FMK
相关产品推荐
相关产品推荐

