0

How to fix problem with forein keys names in laravel while deleting data from database. I changed names in relationships in class file but still does not work. Where do i need make changes? "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'kontakt.id' in 'where clause' (SQL: select * from kontakt where kontakt.id = 1 limit 1)"

class User extends Model
{
    public $table = "user";
    public function kontakt(){

     return $this->hasMany('App\kontakt');
    }
}


class kontakt extends Model
{
    public $table = "kontakt";
    public function user(){

        return $this->belongsTo('App\User','id_user','id_kontakt');
    }
}
Schema::create('user', function (Blueprint $table) {
            $table->bigIncrements('id_user');
            $table->string('imie_user');
            $table->string('nazwisko_user');
            $table->string('haslo_user');
            $table->string('email')->unique();
}
Schema::create('kontakt', function (Blueprint $table) {
            $table->bigIncrements('id_kontakt');
            $table->string('imie_kontakt');
            $table->string('nazwisko_kontakt');
            $table->string('opis_kontakt');
            $table->string('miasto_kontakt');
            $table->string('ulica_kontakt');
            $table->string('nr_bloku_kontakt');
            $table->string('nr_mieszkania_kontakt');
            $table->string('telefon_kontakt');
            $table->string('nr_konta_kontakt');
            $table->string('nip_kontakt');
            $table->unsignedBigInteger('id_user');
            $table->foreign('id_user')->references('id_user')->on('user');
        })


 public function deletekontakt($id_kontakt){

    $kontakt = kontakt::find($id_kontakt);
    $kontakt->delete();
    return redirect('kontakty');
}

1 Answer 1

4

Eloquent will also assume that each table has a primary key column named id. You may define a $primaryKey property to override this convention.

in your kontakt model define primary key:

class kontakt extends Model
{
    public $table = "kontakt";
    protected $primaryKey = 'id_kontakt';

    public function user(){

        return $this->belongsTo('App\User','id_user','id_kontakt');
    }
}

also in User model .

protected $primaryKey = 'id_user';

And for delete, you can also use destroy() method.

kontakt::destroy($id_kontakt);
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah :) and you can directly delete reocrd.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.