So I'm trying to create a simple REST API using Laravel. While testing out the API with creating new items to the database I'm receiving an error:
Illuminate\\Database\\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ( world
. cities
, CONSTRAINT cities_ibfk_1
FOREIGN KEY ( CountryCode
) REFERENCES country
( Code
)) (SQL: insert into cities
( Name
, CountryCode
, District
, Population
, updated_at
, created_at
) values (Valhalla, vlh, Ragnar Alley, 200000000, 2020-02-19 01:07:26, 2020-02-19 01:07:26)) in file C:\\xampp\\htdocs\\myapp\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php on line 669
here's the Controller:
public function createCity(Request $request) {
$city = new City;
$city->Name = $request->Name;
$city->CountryCode = $request->CountryCode;
$city->District = $request->District;
$city->Population = $request->Population;
$city->save();
Model:
class City extends Model
{
protected $table = 'cities';
protected $fillable = ['Name', 'CountryCode', 'District', 'Population'];
}
Help would be appreciated as I can't figure out why I'm getting the error after POST. Thanks in advance.
You try to add vlh
as contry_code
value into your model .but this field refrence to another model that have country
name and in that table there is not any record with this condition and vlh
value is unknown or it.
You can romve relation between these models (if it is possible) or first find the id
of country
that has that code
and then insert it into your model.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.