Home > OS >  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'majors.user_id' in 'where cla
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'majors.user_id' in 'where cla

Time:05-22

I want to display user's major. I've defined relationship between user-major and i created foreignId 'major_id' in user's table. I migrated all migrations successfully. But when i want to display user's major it return error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'majors.user_id' in 'where clause' (SQL: select * from majors where majors.user_id = 1 and majors.user_id is not null limit 1)

model Major.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Major extends Model
{
    use HasFactory;
    // protected $primaryKey = 'info_id';
    protected $guarded=['id'];
    public function faculty(){
        return $this->belongsTo(Faculty::class);
    }

    public function user(){
        return $this->belongsTo(User::class);
    }
}

model User.php

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    // protected $fillable = [
    //     'name',
    //     'email',
    //     'password',
    // ];

    protected $guarded=['id'];
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function getRouteKeyName()
    {
        return 'name';
    }

    public function score(){
        return $this->hasMany(Score::class);
    }

    public function major(){
        return $this->hasOne(Major::class);
    }

}

2021_05_21_042431_create_majors_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateMajorsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('majors', function (Blueprint $table) {
            $table->id();
            $table->foreignId('faculty_id')->constrained();
            $table->string('nama_jurusan');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('majors');
    }
}

2022_05_22_000000_create_users_table.php <?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('major_id');
            // $table->foreignId('major_id')->constrained('majors');
            $table->foreign('major_id')->references('id')->on('majors');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->bigInteger('nrp');
            $table->string('address');
            $table->integer('generation');
            // $table->string('major');
            // $table->string('faculty'); 
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

index.blade.php to display user's major

@extends('dashboard.layouts.main')

@section('container')
<div >
    <h1>Biodata</h1>
    {{-- <h1 >Welcome back, {{auth()->user()->name}}</h1> --}}
    {{-- <div > --}}
</div>
<div >
    <h4>Nama: {{auth()->user()->name}}</h4>
    <h4>Email: {{auth()->user()->email}}</h4>
    <h4>Alamat: {{auth()->user()->address}}</h4>
    <h4>Angkatan: {{auth()->user()->generation}}</h4>
    <h4>Jurusan: {{auth()->user()->major}}</h4>
    <h4>Fakultas: {{auth()->user()->faculty}}</h4>
</div>
@endsection

CodePudding user response:

in the user modal change the relationship to

  public function major(){
        return $this->belongsTo(Major::class);
    }

And When select write

User::with('major')->get();

CodePudding user response:

I think what you have done till is right need to add proper fillable value in models.

you user model should be like this

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
     protected $fillable = [
        'name',
         'email',
         'password',
          'major_id',
          'nrp',
          'address',
          'generation'
     ];

    protected $guarded=['id'];
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function getRouteKeyName()
    {
        return 'name';
    }

    public function score(){
        return $this->hasMany(Score::class);
    }

    public function major(){
        return $this->hasOne(Major::class,'id','major_id');
    }

}

Note : Laravel default conventions are looking user_id on majors table but its not there thats the issue for this case so add your convention to user model like this


    public function major(){
        return $this->hasOne(Major::class,'id','major_id');
    }

  • Related