我目前正在尝试在数据库中的两个模型之间创建一种 Eloquent 关系,一个在 sql 中,一个在 mongodb 中:
<?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',
];
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany|\Jenssegers\Mongodb\Relations\HasMany
*/
public function trends()
{
return $this->hasMany(Trend::class);
}
}
<?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'];
/**
* @return void
*/
protected static function booted()
{
static::addGlobalScope(new AscendingOrderScope);
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function location()
{
return $this->belongsTo(Location::class);
}
}
一旦我尝试调用趋势模型上的 ->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
在数据库中,location_id
字段是用现有位置模型的id正确设置的。
由于它是混合关系,我还添加了 HybridRelation 特征,如包示例中所述(我几乎正在做与示例中完全相同的事情)。
相反(调用 location->trends
可以正常工作)...
我错过了什么?
感谢您的帮助, FMK
最佳答案
通过callstack调试后找到解决方案。 Laravel 似乎不知道在关系模型上使用哪个连接,因此它默认返回到定义了关系的模型之一。 就我而言,趋势是使用 mongodb 连接,laravel 也尝试搜索此连接中的位置。
解决方案是在 SQL 趋势模型上定义连接:
protected $connection = 'mysql';
关于php - Laravel jenssegers/laravel-mongodb ownsTo 关系抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72816979/