Search code examples
laravelphpmyadminwamp

Can't fetch the second table data from or with the first table in Laravel relationship


I can't fetch the second table data from or with the first table in the Laravel relationship.

Error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cars.mec_id' in 'where clause' SELECT * FROM cars WHERE cars.mec_id = 1 AND cars.mec_id IS NOT NULL limit 1

mecs Migration

public function up(): void
{
    Schema::create('mecs', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });
}

cars Migration

public function up(): void
{
    Schema::create('cars', function (Blueprint $table) {
        $table->bigIncrements('id');              // **also used $table->id();**
        $table->string('name');
        $table->unsignedBigInteger('eid');
        $table->foreign('eid')->references('id')->on('mecs');   // **also used foreignId
        $table->timestamps();
    });
}

car Model

function display()
{
    return $this->hasOne(car::class);
}

Controller

class relation extends Controller
{
    function show($id){
        return mec::find($id)->display;   // **also used  ->with(display)
}
}

Solution

  • Since you didn't follow default Laravel naming conventions, based on your relation and model name, Laravel is assuming that your cars table has mec_id column. Looking at the given example above, you're using eid column for that relation. So in order to map out your relation to use that column instead, you have to change the display() relation to this:

    function display()
    {
        return $this->hasOne(car::class, 'eid');
    }
    

    You can read more about it here: https://laravel.com/docs/10.x/eloquent-relationships#one-to-one