skip to Main Content

I’m trying to delete a record with two primary keys, using Eloquent – Laravel.

This is my model

class Like extends Model
{
    //protected $primaryKey = ['crdid', 'usrid'];
    public $timestamps = false;
    use HasFactory;
}

Controller

try{
     $dellike = Like::where('crdid', '=', $like->crdid, 'and')
    ->where('usrid', '=', $like->usrid)->first();
                    $dellike->delete();
   }
   catch(Exception $e){
       return $e->getMessage();
   }

Table definition

Schema::create('likes', function (Blueprint $table) {
        $table->biginteger('crdid');
        $table->biginteger('usrid');
        $keys = array('crdid', 'usrid');
        $table->primary($keys);
    });

However, it gives me the below error;

 Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: delete from `likes` where `id` is null)

I believe the ‘id’ is the default primary key used by Eloquent, but I’m not using it.

How should I define that, I’m not using the default primary key? or what is the correct way to delete the record with composite primary keys? Any help would be highly appreciated.

2

Answers


  1. As Laravel Eloquent Docs says:

    Eloquent requires each model to have at least one uniquely identifying "ID" that can serve as its primary key. "Composite" primary keys are not supported by Eloquent models. However, you are free to add additional multi-column, unique indexes to your database tables in addition to the table’s uniquely identifying primary key.

    So you can’t use some methods of eloquent.

    But seeing your code, looks like you are trying to create a model for a relationship pivot table (many to many between user and crd (what is crd?! no reason to abreviatte here.)

    Try defining a many to many relationship on your user and crd model.

    Also laravel naming convention for key columns is: model_name_id for a model named ModelName

    But, just to delete, you can skip the first in your query:

    Like::where('crdid', '=', $like->crdid, 'and')
        ->where('usrid', '=', $like->usrid)->delete();
    

    This happens because when you delete a model (your attempt) laravel uses the primary key field (defaults to id) as where condition. But manually querying, you are defining the where clauses of the delete.

    Login or Signup to reply.
  2. Just create additionnal column named id in the table as unique with auto-increment option. Eloquent will use it to delete each row with delete function.
    Example with Laravel 5.5 :

    $logement = Logement::findOrFail($id);
    $commodites = Commodites_logement::all()->where('logement_id','=',$logement->id);
    foreach ($commodites as $commodite) {
       $commodite->delete();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search