Laravel Eloquent以不同的关系作为关键的多对多关系

I have the following models

Category
    id           // we don't want to use this one for the relation
    category_id  // we want to use this

Product
    id

CategoryProduct
    product_id  // points to "id" on products table
    category_id // points to **category_id** on categories table

I have the Product model set up as follows (only the most recent variation).

class Product {
    public function categories() {
        return $this->belongsToMany('Category', 'categories_products', 'category_id');
    }
}

When I try to get a product with categories as follows...

Product::with('categories')->get();

I either get the wrong categories because the query is using id on categories as the foreign key. I need it to be using category_id on the categories table.

Or I get none at all. I can't seem to hash out how to set up which columns to use on the belongsToMany method.

Try this follow,

    class Product {
          public function categories() {
              return $this->belongsToMany('Category', 'categories_products', 'product_id','category_id');
          }
    }