-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Description
- Laravel-mongodb Version: 3.8.2
- PHP Version: 7.4.13
- Database Driver & Version: 1.9.0
Description:
Adding a mysql relation to a mongodb model causes the given error when fetching the relation.
{
"exception": "Error"
"file": "/var/www/project/vendor/laravel/framework/src/Illuminate/Database/Connection.php"
"line": 338
"message": "Call to a member function prepare() on null"
}
My model class
use App\Models\User;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Jenssegers\Mongodb\Eloquent\Model;
class Draft extends Model
{
protected $collection = 'survey_drafts';
protected $connection = 'mongodb';
protected $attributes = [
'questions' => [],
];
public function owner(): BelongsTo
{
return $this->belongsTo(User::class, 'owner_id', 'id');
}
}
The User class uses the default MySQL connection.
Upon investigation further, I saw that Connection::getPdoForSelect
is being called on the MongoDB connection instance, where the $pdo
is NULL. Therefore throwing the error when trying to retrieve the PDO class for some reason.
The cause for this is that the MySQL User
model does not have a $connection
property defined as it should pick the default mysql
connection when it's not specifically defined otherwise (as its done with the mongodb model).
This is being done in HasRelationships::newRelatedInstance()
. When being used as a relation to a mongodb model the $this->connection
is a mongodb connection.
The only way to fix this currently is to add a
$connection = 'mysql'
to all MySQL models that are being used as relations to a mongodb model. In the given example, to the User model