phplaravelmongodbeloquentlaravel-mongodb

Laravel jenssegers/laravel-mongodb belongsTo relationship throwing error


I'm currently trying to create a eloquent relationship between two models in my database, one in sql and on in 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);
    }
}

Once i try to call the ->location relationship on the Trend model I only get the following error:

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

In the database the location_id field is corretly set with an id of an existing Location model. Since it is a hybrid relation I also added the HybridRelation trait as described in the packages example (I'm nearly doing the exact stuff as in the example).

The other way around (calling location->trends is working without a problem)...

What am I missing?

Thanks for your help, FMK


Solution

  • Found the solution after debugging through the callstack. Laravel seems to does not know which connection to use on the relationship model so it defaults back to the one of the model with the relationship defined. In my case the trend was using the mongodb connection and laravel tried to search for the location in this connection aswell.

    Solution was was to define the connection on the SQL Trend model aswell:

    protected $connection = 'mysql';