Creating a polymorphic one to many relationship
jlafosse opened this issue · comments
- Corcel Version: 4.0.0
- Framework Name & Version: Laravel 7.0.0
- PHP Version: 7.3.28
- Database Driver & Version: mysql 5.5.68-MariaDB
https://laravel.com/docs/7.x/eloquent-relationships#one-to-many-polymorphic-relations
I am trying to create a polymorphic one to many relationship (morphMany & morphTo) with limited success. I have a Post model that extends the \Corcel\Model\Post and uses a wordpress connection and a PostTrack model that extends the Illuminate\Database\Eloquent\Model and uses my mysql connection.
The problem I run into is when I attempt to save() via the relationship (https://laravel.com/docs/7.x/eloquent-relationships#the-save-method. Since the Post model connection has been set to wordpress, the save attempts to save the model (PostTrack) using wordpress, not mysql.
The only way that I have successfully gotten this to work is by adding newModelQuery() to my PostTrack model and explicitly setting the connection to mysql (even though the protected $connection is already set to mysql). I am thinking there must be a better/cleaner way to do this in the Post model. I have tried extending the morphMany() method in a similar fashion as the Corcel model does for other relationships but have not had much success.
I have included some code examples below. Any help would be appreciated - Thanks!
class Post extends \Corcel\Model\Post
{
protected $connection = 'wordpress';
public function postTracks()
{
return $this->morphMany('App\Models\Plus\PostTrack', 'postable');
}
public function likesCount()
{
return $this->postTracks->sum('like_score');
}
}
class PostTrack extends Illuminate\Database\Eloquent\Model
{
protected $connection = 'mysql';
protected $table = 'post_tracks';
public function newModelQuery()
{
$this->setConnection('mysql');
$modelQuery = parent::newModelQuery();
return $modelQuery;
}
public function postable()
{
return $this->morphTo();
}
public function scopeLiked($query)
{
return $query->where('like_flag', 1);
}
}
This is the relationship I attempted to add in my Post model but with no success:
public function morphMany($related, $name, $type = NULL, $foreignKey = NULL, $localKey = NULL)
{
$foreignKey = $foreignKey ?: $this->getForeignKey();
$instance = $this->setInstanceConnection(
new $related()
);
$localKey = $localKey ?: $this->getKeyName();
return new MorphMany($instance->newQuery(), $this, $name, $type, $foreignKey, $localKey);
}