Laravel 5 Eloquent belongsTo() foreign key won't work

8.9k views Asked by At

I found out that naming of the column in Schema::create() can affect creating constrains, so it can't be found by Model in later queries.

Schema (simplefied):

Schema::create('page_elements', function(Blueprint $table)
{
    $table->increments('id');
    $table->integer('page_element_type_id')->unsigned();
    $table->foreign('page_element_type_id')->references('id')->on('page_element_types')->onUpdate('cascade')->onDelete('restrict');
    $table->timestamps();
});

And when I call

PageElement::find(1)->first()->type()->get()

I get empty collection.

After changing this 2 lines in Shema (only change is page_element_type_id into type_id):

$table->integer('type_id')->unsigned();
$table->foreign('type_id')->references('id')->on('page_element_types')->onUpdate('cascade')->onDelete('restrict');

I got the 1 element in collection, as it should.

Anyone knows if there is some naming issue or rule, regarding this columns with constrains?

EDID: Declaration of type() in Model, as requested:

public function type()
{
    return $this->belongsTo('App\PageElementType');
}
1

There are 1 answers

4
hfingler On

Can you show your type function?

I would bet you did not use the second parameter to set the name of the column that has the foreign key, so change it to:

return $this->belongsTo('App\YourModel', 'page_element_type_id');