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
carsWHEREcars.mec_id= 1 ANDcars.mec_idIS 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)
}
}
Since you didn't follow default Laravel naming conventions, based on your relation and model name, Laravel is assuming that your
carstable hasmec_idcolumn. Looking at the given example above, you're usingeidcolumn for that relation. So in order to map out your relation to use that column instead, you have to change thedisplay()relation to this:You can read more about it here: https://laravel.com/docs/10.x/eloquent-relationships#one-to-one