Q:

Laravel pivot tables with non primary keys

In Laravel, I have a model which has a custom primary key.  I have created a pivot table which has to use the unique incrementing key so I am unable to get any pivot data. 
Media Model
class Media
{
    protected $primaryKey = 'ref_id';
    public $incrementing = false;

    ...
}

Page Model
class Page
{
    public function media()
    {
        return $this->belongsToMany('App\Models\Media');
    }

    ...
}

Pivot Table
+----------+---------+
| media_id | page_id |
+----------+---------+
|     1    |    15   |
+----------+---------+
|     5    |    27   |
+----------+---------+

PageController
$pages = Page::with('media')->get();  

This is resulting in the following sql statement:
select 
    media.*,  media_page.page_id as pivot_page_id, 
    media_page.media_id as pivot_media_id 
from media inner join media_page on media.ref_id = media_page.media_id
where media_page.page_id in ('15', '27')

As you can see on line 4 of the sql statement, it is referencing media.ref_id instead of media.id and so obviously no results are returned.  I understand why this is happening.   What I need to know is how can I update the media method in my PageController so it uses id instead of ref_id for this one query.  I cannot change the primary key in the media model as this is heavily used elsewhere.  I have tried the following but it seems to have no effect. 
Page Model
class Page
{
    public function media()
    {
        $media = new Media();
        $media->setPrimaryKey('id');

        return $this->belongsToMany($media);
    }

    ...
}

Thanks

A:

If you check the documentation at https://laravel.com/docs/5.6/eloquent-relationships you will see that belongsToMany() also accept other parameters to set how to join the tables return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');

