jbehrens94
jbehrens94

Reputation: 2406

Laravel one-to-one relationship fails

I created two migrations, because I wanted to create a one-to-one relationship between Trend and TrendExplanation.

Schema::create('trend_explanations', function (Blueprint $table) {
    $table->increments('id');
    $table->text('demographical')->nullable();
    $table->text('economical')->nullable();
    $table->text('social')->nullable();
    $table->text('technological')->nullable();
    $table->text('ecological')->nullable();
    $table->text('political')->nullable();
    $table->timestamps();
});

This is the migration for the Trend model:

Schema::create('trends', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('explanation_id')->unsigned();
    $table->foreign('explanation_id')->references('id')->on('trend_explanations');
    $table->string('name');
    $table->date('date');
    $table->text('description');
    $table->timestamps();
});

So in the models I did the following additions:

class Trend extends Model
{
    public function explanation()
    {
        return $this->hasOne(TrendExplanation::class);
    }
}

And of course I created a seeder to test it out:

$trend = new Trend();
$trend->name = "Something";
$trend->description = "Description";

$explanation = new TrendExplanation();
// ...
$trend->explanation()->save($explanation);
$trend->save();

And when I run it, I receive the error: [Illuminate\Database\QueryException] SQLSTATE[42S22]: Column not found: 1054 Unknown column 'trend_id' in 'field list'.

How does this happen? I don't understand what I did wrong here.

Upvotes: 2

Views: 335

Answers (1)

aynber
aynber

Reputation: 23011

You can specify the foreign and local keys when specifying the relationship. It usually goes

$this->hasOne(Class, foreign, local);

So your definition would be:

return $this->hasOne(TrendExplanation::class, 'id', 'explanation_id');

Upvotes: 2

Related Questions