Reputation: 604
Here is my parent model which uses default database connection of mysql type.
class Property extends Model
{
use SoftDeletes, HybridRelations;
protected $hidden = [];
public function propertyType()
{
return $this->hasOne('App\RentHisto\Models\PropertyType');
}
}
And here is my mongodb model which has relation with property
class PropertyDetail extends Model
{
protected $connection = "mongodb";
protected $collection = "property_details";
public function propertyDetails(){
return $this->belongsTo(Property::class);
}
}
And here is my query to get the data of property with property_details
$properties = Property::with('propertyDetails')->get();
But the problem is that when I'm trying to get data it returns null in case of property details. It maybe due to, we are calling the mongodb model data on the connection with mysql instance. So is there any way by which I can make relationship(hasOne) between two models i.e mysql model and mongodb model. Thanks !
Upvotes: 3
Views: 3932
Reputation: 81
In case of a Hybrid database, you need to define $connection in both models as per your database usage.
Try defining $connection in your Property model.
protected $connection = 'mysql';
After defining connection, try defining the relationship with foreign key and local key parameters in both models.
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');
}
.
.
}
Where property_id is the attribute resides in your mongodb.
It must have same datatype as id attribute in your MySql - property table.
If you are using id as primary key on your MySQL Property table then make sure your property_id in mongodb also stored as interger. type cast it in case its string.
// 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');
}
.
.
}
Upvotes: 6