Reputation: 1408
In the official documentation I can see a method destroy
where you can put a list of Primary Keys and it deletes all the data in the list.
ModelName::destroy([1,2,3]);
But what if we have a custom PK? I've tried to do it with a field called code
which is a string but it says:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `paises` where `id` in ())
Is there a way to tell Laravel that the primary key is not called id
?
Something like
ModelName::destroy(['AL', 'ES', 'FR'], 'code');
Upvotes: 1
Views: 427
Reputation: 47380
From the documentation:
Eloquent will also assume that each table has a primary key column named id. You may define a protected $primaryKey property to override this convention.
So, in your model:
class User extends Model
{
protected $primaryKey = 'yourPrimaryKey';
}
Since it appears you are using a string-based PK, the following paragraph in the docs is also relevant.
In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false. If your primary key is not an integer, you should set the protected $keyType property on your model to string.
So your model should also include:
protected $incrementing = false;
protected $keyType = 'string';
Upvotes: 2