【问题标题】:Mysql and mongodb relationship in laravellaravel中mysql和mongodb的关系
【发布时间】:2019-02-22 13:10:05
【问题描述】:

这是我的父模型,它使用 mysql 类型的默认数据库连接。

class Property extends Model
{
  use SoftDeletes, HybridRelations;

  protected $hidden = [];

  public function propertyType()
  {
     return $this->hasOne('App\RentHisto\Models\PropertyType');
  }
}

这是我的 mongodb 模型,它与属性有关系

class PropertyDetail extends Model
{

 protected $connection = "mongodb";

 protected $collection = "property_details"; 

 public function propertyDetails(){
    return $this->belongsTo(Property::class);
 }
}

这是我使用 property_details 获取属性数据的查询

$properties = Property::with('propertyDetails')->get();

但问题是,当我尝试获取数据时,如果是属性详细信息,它会返回 null。这可能是由于,我们在与 mysql 实例的连接上调用了 mongodb 模型数据。那么有什么方法可以在两个模型(即mysql模型和mongodb模型)之间建立关系(hasOne)。谢谢!

【问题讨论】:

标签: mysql mongodb laravel eloquent relationship


【解决方案1】:

如果是混合数据库,您需要根据您的数据库使用情况在两个模型中定义 $connection。

尝试在您的属性模型中定义 $connection

protected $connection = 'mysql';

定义连接后,尝试在两个模型中定义与外键和本地键的关系参数。

class Property extends Model
{
    use HybridRelations;

    protected $connection = 'mysql';
    protected $table = 'YOUR_MYSQL_TABLE';    
    /**
     * Relationship to Mongodb Model
     */
    public function propertyType()
    {
        return $this->hasMany(PropertyDetail::class, 'property_id', 'id');
    }
.
.
}

property_id 是驻留在 mongodb 中的属性。

它必须与您的 MySql - 属性表中的 id 属性具有相同的数据类型。

如果您在 MySQL 属性表上使用 id 作为主键,请确保您在 mongodb 中的 property_id 也存储为整数。类型转换它以防它的字符串。

// Mongodb Model
class PropertyDetail extends Model
{
    protected $connection = 'mongodb';
    protected $collection = 'property_details';

    /**
     * Relationship to MySql
     */
    public function propertyDetails()
    {
        return $this->belongsTo(Property::class, 'property_id', 'id');
    }
.
.
}

【讨论】:

猜你喜欢
  • 2014-08-04
  • 2017-03-11
  • 2012-05-04
  • 1970-01-01
  • 1970-01-01
  • 2017-05-18
  • 2019-01-30
  • 1970-01-01
  • 2022-09-23
相关资源
最近更新 更多