Tan Tan - 1 month ago 16
MySQL Question

Mysql and mongodb relationship in laravel 5.3

I tried to make relationship to mysql with mongodb on laravel 5.3

First i created Content Model with mysql connection.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Content extends Model
{
/**
* The connection name for the model.
*
* @var string
*/
protected $connection = 'mysql';

/**
*
*
*/
public function category()
{
return $this->hasOne('App\Category', 'id', 'cid');
}

/**
*
*
*
*/
public function tags()
{
return $this->hasMany('App\Tag', 'cid', 'id');
}
}


And then i created Tag Model with mongodb.

<?php

namespace App;

use Jenssegers\Mongodb\Eloquent\Model;

class Tag extends Model
{
/**
* The connection name for the model.
*
* @var string
*/
protected $connection = 'mongodb';
protected $collection = 'tags';

/**
* Fillable fields
*
* @var array
*/
protected $guarded = ['_id'];

/**
*
*
*/
public function content()
{
return $this->belongsTo('App\Content', 'id', 'cid');
}
}


Everything okey so far but when i try to get data, who get empty.

$contents = Content::with('category')->with('tags')->get();

dd($contents[0]->tags);


I googled it but i couldn't find anything. Can you offer me any way?

Answer

According to Moloquent documentation at https://moloquent.github.io/master/relations/#mysql-relations you will need to use Moloquent\Eloquent\HybridRelations trait in your sql model (App\Content).