I have the following schema:
objects
table Schema::create('objects', function(Blueprint $table) {
$table->increments('object_id');
});
With a relation of:
public function tags() {
return $this->belongsToMany('Tag', 'objects_tags_pivot', '?', '?');
}
tags
table: Schema::create('tags', function(Blueprint $table) {
$table->increments('tag_id');
});
With a relation of:
public function objects() {
return $this->belongsToMany('Object', 'objects_tags_pivot', '?', '?');
}
And a pivot between them for the many to many relationship present:
Schema::create('objects_tags_pivot', function(Blueprint $table) {
$table->increments('object_tags_id');
$table->integer('object_id')->unsigned();
$table->integer('tag_id')->unsigned();
});
My question is what to insert into the relationship parameters where I currently have question marks? The Laravel 4.2 documentation suggests that the third parameter is $foreignKey
and the fourth is $localKey
. This isn't very helpful.
Every attempt at matching object_id
and tag_id
up with these parameter, or leaving them blank, has resulted in one or more of the fields on the pivot table being 0
. Not useful at all.
What order should I specify each parameter in?
Have you ever tried leaving them null? Laravel will already make foreign and local / other key assumptions based on the table name of the relation. For example, since the objects
table model name is Object
it will guess that the foreign key is named object_id
. Also, since the tags
model name is Tag
, it will guess tag_id
for the local / other key in a relationship.
If you want to fill them out manually, you need to insert the column names that indicate how the relationship is linked. For example:
public function tags()
{
$this->belongsToMany('Tag', 'objects_tag_pivot', 'object_id', 'tag_id');
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments