I tried doing the same with a regular Many-to-Many relation as well, and using the name property on my Tag model as the primary key (since that just seems like a better table design). So:
class Tag extends Model
{
protected $primaryKey = 'name';
public $incrementing = false;
public function pages()
{
return $this->belongsToMany('App\Page', 'page_tag', 'tag_name', 'page_id')->withTimestamps();
}
}
and with the Migrations:
Schema::create('tags', function (Blueprint $table) {
$table->string('name');
$table->timestamps();
$table->primary('name');
});
Schema::create('page_tag', function (Blueprint $table) {
$table->increments('id');
$table->string('tag_name');
$table->foreign('tag_name')->references('name')->on('tags')->onDelete('cascade');
$table->integer('page_id')->unsigned();
$table->foreign('page_id')->references('id')->on('pages')->onDelete('cascade');
$table->timestamps();
});
This, however, results in the same error:
[Illuminate\Database\QueryException]
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name' in 'field list' (SQL: insert into `page_tag` (`created_at`, `
name`, `page_id`, `tag_name`, `updated_at`) values (2016-08-22 21:18:30, consequatur, 1, 0, 2016-08-22 21:18:30))
Not only that, but Laravel is actually trying to insert the tag name "consequatur" in the non-existing name field while it is trying to insert 0 in the actual foreign key tag_name field!
Frustrated, I go to bed with no solution in sight.
/Jens Roland