我尝试在 laravel 5.3 上使用 mongodb 与 mysql 建立关系
首先,我使用 mysql 连接创建了内容模型。
<?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');
}
}
然后我用 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');
}
}
到目前为止一切正常,但是当我尝试获取数据时,谁会变空。
$contents = Content::with('category')->with('tags')->get();
dd($contents[0]->tags);
最佳答案
根据位于 https://moloquent.github.io/master/relations/#mysql-relations 的 Moloquent 文档你需要在你的 sql 模型 (App\Content) 中使用 Moloquent\Eloquent\HybridRelations
trait。
关于laravel 5.3中mysql和mongodb的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40310342/