-
Codinglander Member
  
-
Posts: 62
Threads: 14
Joined: Jan 2018
Reputation:
2
02-07-2021, 03:56 AM
(This post was last modified: 02-07-2021, 12:48 PM by Codinglander.)
Hi community.
During the development of a project I get an error which I cannot solve.
The error message is:
_______________________________________________________________
mysqli_sql_exeption #1452
Cannot add or update a child row: a foreign key constraint fails
____________________________________________________________________
The associated controller function:
PHP Code: public function update($id) { $homegame = $this->getHomegameOr404($id);
$post = $this->request->getPost();
unset($post['user_id']);
$homegame->fill($post);
if(! $homegame->hasChanged()){ return redirect()->back() ->with('warning',lang('App.messages.noupdate')) ->withInput(); } if($this->homegame_model->save($homegame)) {
return redirect()->to("/homegames/show/$id") ->with('info', lang('App.messages.homegame_edited')); } else { return redirect()->back() ->with('errors', $this->homegame_model->errors()) ->with('warning', lang('App.messages.invalid')) ->withInput(); } }
The associated tables: (as images)
HOMEGAMES
USERS
How to solve this error ? Any hints ?
Greetings
Kigh...
-
paliz Member
  
-
Posts: 236
Threads: 19
Joined: Oct 2020
Reputation:
1
this rest full cotroller look at code
controller
PHP Code: <?php
namespace App\Controllers\Api;
use App\Entities\NewsPostEntity; use App\Libraries\ParameterDataInput; use CodeIgniter\HTTP\ResponseInterface; use \App\Models\NewsPostModal;
class NewsPost extends ApiController {
/** * index function * @method : GET */ public function index() { $newsPostModel = new NewsPostModal();
$parameterDataInput = new ParameterDataInput();
$parameterDataInput->receiveParameters();
$result = $newsPostModel->select('news_post.*,news_category.name_en as category_name_en,news_category.name_fa as category_name_fa,news_sub_category.name_en as sub_category_name_en,news_sub_category.name_fa as sub_category_name_fa,users.username ,users.first_name, users.last_name')->join('news_category', 'news_category.id = news_post.category_id', 'left') ->join('news_sub_category', 'news_sub_category.id = news_post.sub_category_id', 'left') ->join('users', 'users.id = news_post.user_id', 'left') ->like('news_post.' . $parameterDataInput->getFilterExplode('key'), $parameterDataInput->getFilterExplode('value'))->orderBy($parameterDataInput->getSortExplode('key'), $parameterDataInput->getSortExplode('value'))->paginate(10, 'default', $parameterDataInput->getPage());
return $this->respond([ 'data' => $result, 'pager' => $newsPostModel->pager->getDetails() ], ResponseInterface::HTTP_OK, 'get all news post');
}
/** * show function * @method : GET with params ID */ public function show($id = null) {
$newsPostModel = new NewsPostModal();
$result = $newsPostModel->select('news_post.*,news_category.name_en as category_name_en,news_category.name_fa as category_name_fa,news_sub_category.name_en as sub_category_name_en,news_sub_category.name_fa as sub_category_name_fa,users.username ,users.first_name, users.last_name') ->join('news_category', 'news_category.id = news_post.category_id', 'left') ->join('news_sub_category', 'news_sub_category.id = news_post.sub_category_id', 'left') ->join('users', 'users.id = news_post.user_id', 'left') ->where('news_post.id', $id)->paginate(1, 'default');
return $this->respond([
'data' => $result, 'pager' => $newsPostModel->pager->getDetails() ], ResponseInterface::HTTP_OK, 'get news post information');
}
/** * create function * @method : POST */ public function create() { $newsPostModel = new NewsPostModal(); $newsPostEntity = new NewsPostEntity(); if ($this->request->getJSON()) {
$rules = [ 'title_fa' => 'required|min_length[3]|max_length[255]', 'title_en' => 'required|min_length[3]|max_length[255]', 'body_en' => 'required', 'body_fa' => 'required', 'category_id' => 'required', 'sub_category_id' => 'required',
];
if (!$this->validate($rules)) {
return $this->respond([ 'error' => $this->validator->getErrors(), 'success' => false ], ResponseInterface::HTTP_NOT_ACCEPTABLE, 'error during news post validate ');
};
$newsPostEntity->user_id = $this->userId; $newsPostEntity->sub_category_id = $this->request->getJSON()->sub_category_id; $newsPostEntity->category_id = $this->request->getJSON()->category_id; $newsPostEntity->title_fa = $this->request->getJSON()->title_fa; $newsPostEntity->title_en = $this->request->getJSON()->title_en; $newsPostEntity->body_en = $this->request->getJSON()->body_en; $newsPostEntity->body_fa = $this->request->getJSON()->body_fa; $newsPostEntity->disableStatus(); $newsPostEntity->createdAt(); $newsPostEntity->initPicture();
if (!$newsPostModel->save($newsPostEntity)) {
return $this->respond([ 'error' => $newsPostModel->errors(), 'success' => false, ], ResponseInterface::HTTP_BAD_REQUEST, ' cant save news post ');
}
return $this->respond([ 'data' => '' ], ResponseInterface::HTTP_CREATED, ' news post save successfully '); }
}
/** * update function * @method : PUT or PATCH */ public function update($id = null) { $newsPostModel = new NewsPostModal(); $newsPostEntity = new NewsPostEntity(); if ($this->request->getJSON()) { //get request from Vue Js $json = $this->request->getJSON(); if (!isset($id)) { $id = $json->id; }
$rules = [ 'title_fa' => 'required|min_length[3]|max_length[255]', 'title_en' => 'required|min_length[3]|max_length[255]', 'body_en' => 'required', 'body_fa' => 'required', 'category_id' => 'required', 'sub_category_id' => 'required', 'picture' => 'required', 'status' => 'required',
];
if (!$this->validate($rules)) { return $this->respond([ 'error' => $this->validator->getErrors(), 'success' => false ], ResponseInterface::HTTP_NOT_ACCEPTABLE, 'error during edit news post validate ');
}
$newsPost = $newsPostModel->where('id', $id)->first();
if (is_null($newsPost)) {
return $this->respond([ 'error' => $this->validator->getErrors(), 'success' => false ], ResponseInterface::HTTP_NOT_FOUND, ' news post did not exist ');
}
$newsPostEntity->user_id = $this->userId; $newsPostEntity->category_id = $this->request->getJSON()->category_id; $newsPostEntity->sub_category_id = $this->request->getJSON()->sub_category_id; $newsPostEntity->title_fa = $this->request->getJSON()->title_fa; $newsPostEntity->title_en = $this->request->getJSON()->title_en; $newsPostEntity->body_en = $this->request->getJSON()->body_en; $newsPostEntity->body_fa = $this->request->getJSON()->body_fa; $newsPostEntity->status = $this->request->getJSON()->status; $newsPostEntity->picture = $this->request->getJSON()->picture; $newsPostEntity->updatedAt();
if (!$newsPostModel->update($id, $newsPostEntity)) {
return $this->respond([ 'error' => $newsPostModel->errors(), 'success' => false, ], ResponseInterface::HTTP_BAD_REQUEST, 'error news post ');
}
return $this->respond([ ], ResponseInterface::HTTP_OK, ' news post information updated '); }
}
/** * edit function * @method : DELETE with params ID */ public function delete($id = null) {
$newsPostModel = new NewsPostModal();
$isExist = $newsPostModel->find($id); if ($isExist) { $newsPostModel->delete($id);
} return $this->respond([ ], ResponseInterface::HTTP_OK, ' news post delete it');
}
}
model
PHP Code: <?php namespace App\Models;
use App\Entities\NewsPostEntity; use CodeIgniter\Model;
class NewsPostModal extends Model { protected $table = 'news_post'; protected $primaryKey = 'id'; protected $returnType = NewsPostEntity::class; protected $allowedFields = [ 'sub_category_id', 'category_id', 'picture', 'user_id', 'title_en', 'title_fa', 'body_en', 'body_fa', 'status', 'created_at', 'updated_at', 'deleted_at' ];
protected $useSoftDeletes = false; protected $useTimestamps = true; protected $createdField = 'created_at'; protected $updatedField = 'updated_at'; protected $deletedField = 'deleted_at'; protected $validationRules = [ 'title_fa' => 'required|min_length[3]|max_length[255]', 'title_en' => 'required|min_length[3]|max_length[255]', 'picture' => 'required|min_length[3]|max_length[255]', 'body_en' => 'required', 'body_fa' => 'required', ]; protected $validationMessages = []; protected $skipValidation = false;
}
entity
PHP Code: <?php namespace App\Entities;
use \CodeIgniter\Entity; use CodeIgniter\I18n\Time;
class NewsPostEntity extends Entity {
public function __construct(array $data = null) { parent::__construct($data);
}
protected $id; protected $sub_category_id; protected $category_id; protected $user_id; protected $title_en; protected $picture; protected $title_fa; protected $body_en; protected $body_fa;
protected $status; protected $created_at; protected $updated_at; protected $deleted_at;
protected $attributes = [ 'id' => null, 'sub_category_id' => null, 'category_id' => null, 'user_id' => null, 'title_en' => null, 'title_fa' => null, 'body_en' => null, 'body_fa' => null, 'status' => null, 'picture' => null, 'created_at' => null, 'updated_at' => null, 'deleted_at' => null, ]; protected $datamap = [ ];
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $casts = [ 'status' => 'boolean', ];
protected $permissions = [];
protected $roles = [];
public function disableStatus() { $this->attributes['status'] = 0; return $this;
}
public function enableStatus() { $this->attributes['status'] = 1;
return $this; }
public function isStatus(): bool { return isset($this->attributes['status']) && $this->attributes['status'] == true; }
public function createdAt() {
// date_default_timezone_set('Asia/Tehran'); $this->attributes['created_at'] = date('Y-m-d H:i:s', time()); // $this->attributes['created_at'] = new Time(date('Y-m-d H:i:s', time()), 'UTC'); return $this; }
public function updatedAt() {
// date_default_timezone_set('Asia/Tehran'); $this->attributes['updated_at'] = date('Y-m-d H:i:s', time());
return $this; }
public function initPicture() { $this->attributes['picture'] = 'copy image link here!'; return $this;
}
public function editPicture() {
$this->attributes['picture'] = 'public/upload/news/thumbnail' . $this->attributes['picture'];
return $this; }
}
Enlightenment Is Freedom
-
Codinglander Member
  
-
Posts: 62
Threads: 14
Joined: Jan 2018
Reputation:
2
(02-07-2021, 10:04 AM)paliz Wrote: this rest full cotroller look at code
controller
PHP Code: <?php
namespace App\Controllers\Api;
use App\Entities\NewsPostEntity; use App\Libraries\ParameterDataInput; use CodeIgniter\HTTP\ResponseInterface; use \App\Models\NewsPostModal;
class NewsPost extends ApiController {
/** * index function * @method : GET */ public function index() { $newsPostModel = new NewsPostModal();
$parameterDataInput = new ParameterDataInput();
$parameterDataInput->receiveParameters();
$result = $newsPostModel->select('news_post.*,news_category.name_en as category_name_en,news_category.name_fa as category_name_fa,news_sub_category.name_en as sub_category_name_en,news_sub_category.name_fa as sub_category_name_fa,users.username ,users.first_name, users.last_name')->join('news_category', 'news_category.id = news_post.category_id', 'left') ->join('news_sub_category', 'news_sub_category.id = news_post.sub_category_id', 'left') ->join('users', 'users.id = news_post.user_id', 'left') ->like('news_post.' . $parameterDataInput->getFilterExplode('key'), $parameterDataInput->getFilterExplode('value'))->orderBy($parameterDataInput->getSortExplode('key'), $parameterDataInput->getSortExplode('value'))->paginate(10, 'default', $parameterDataInput->getPage());
return $this->respond([ 'data' => $result, 'pager' => $newsPostModel->pager->getDetails() ], ResponseInterface::HTTP_OK, 'get all news post');
}
/** * show function * @method : GET with params ID */ public function show($id = null) {
$newsPostModel = new NewsPostModal();
$result = $newsPostModel->select('news_post.*,news_category.name_en as category_name_en,news_category.name_fa as category_name_fa,news_sub_category.name_en as sub_category_name_en,news_sub_category.name_fa as sub_category_name_fa,users.username ,users.first_name, users.last_name') ->join('news_category', 'news_category.id = news_post.category_id', 'left') ->join('news_sub_category', 'news_sub_category.id = news_post.sub_category_id', 'left') ->join('users', 'users.id = news_post.user_id', 'left') ->where('news_post.id', $id)->paginate(1, 'default');
return $this->respond([
'data' => $result, 'pager' => $newsPostModel->pager->getDetails() ], ResponseInterface::HTTP_OK, 'get news post information');
}
/** * create function * @method : POST */ public function create() { $newsPostModel = new NewsPostModal(); $newsPostEntity = new NewsPostEntity(); if ($this->request->getJSON()) {
$rules = [ 'title_fa' => 'required|min_length[3]|max_length[255]', 'title_en' => 'required|min_length[3]|max_length[255]', 'body_en' => 'required', 'body_fa' => 'required', 'category_id' => 'required', 'sub_category_id' => 'required',
];
if (!$this->validate($rules)) {
return $this->respond([ 'error' => $this->validator->getErrors(), 'success' => false ], ResponseInterface::HTTP_NOT_ACCEPTABLE, 'error during news post validate ');
};
$newsPostEntity->user_id = $this->userId; $newsPostEntity->sub_category_id = $this->request->getJSON()->sub_category_id; $newsPostEntity->category_id = $this->request->getJSON()->category_id; $newsPostEntity->title_fa = $this->request->getJSON()->title_fa; $newsPostEntity->title_en = $this->request->getJSON()->title_en; $newsPostEntity->body_en = $this->request->getJSON()->body_en; $newsPostEntity->body_fa = $this->request->getJSON()->body_fa; $newsPostEntity->disableStatus(); $newsPostEntity->createdAt(); $newsPostEntity->initPicture();
if (!$newsPostModel->save($newsPostEntity)) {
return $this->respond([ 'error' => $newsPostModel->errors(), 'success' => false, ], ResponseInterface::HTTP_BAD_REQUEST, ' cant save news post ');
}
return $this->respond([ 'data' => '' ], ResponseInterface::HTTP_CREATED, ' news post save successfully '); }
}
/** * update function * @method : PUT or PATCH */ public function update($id = null) { $newsPostModel = new NewsPostModal(); $newsPostEntity = new NewsPostEntity(); if ($this->request->getJSON()) { //get request from Vue Js $json = $this->request->getJSON(); if (!isset($id)) { $id = $json->id; }
$rules = [ 'title_fa' => 'required|min_length[3]|max_length[255]', 'title_en' => 'required|min_length[3]|max_length[255]', 'body_en' => 'required', 'body_fa' => 'required', 'category_id' => 'required', 'sub_category_id' => 'required', 'picture' => 'required', 'status' => 'required',
];
if (!$this->validate($rules)) { return $this->respond([ 'error' => $this->validator->getErrors(), 'success' => false ], ResponseInterface::HTTP_NOT_ACCEPTABLE, 'error during edit news post validate ');
}
$newsPost = $newsPostModel->where('id', $id)->first();
if (is_null($newsPost)) {
return $this->respond([ 'error' => $this->validator->getErrors(), 'success' => false ], ResponseInterface::HTTP_NOT_FOUND, ' news post did not exist ');
}
$newsPostEntity->user_id = $this->userId; $newsPostEntity->category_id = $this->request->getJSON()->category_id; $newsPostEntity->sub_category_id = $this->request->getJSON()->sub_category_id; $newsPostEntity->title_fa = $this->request->getJSON()->title_fa; $newsPostEntity->title_en = $this->request->getJSON()->title_en; $newsPostEntity->body_en = $this->request->getJSON()->body_en; $newsPostEntity->body_fa = $this->request->getJSON()->body_fa; $newsPostEntity->status = $this->request->getJSON()->status; $newsPostEntity->picture = $this->request->getJSON()->picture; $newsPostEntity->updatedAt();
if (!$newsPostModel->update($id, $newsPostEntity)) {
return $this->respond([ 'error' => $newsPostModel->errors(), 'success' => false, ], ResponseInterface::HTTP_BAD_REQUEST, 'error news post ');
}
return $this->respond([ ], ResponseInterface::HTTP_OK, ' news post information updated '); }
}
/** * edit function * @method : DELETE with params ID */ public function delete($id = null) {
$newsPostModel = new NewsPostModal();
$isExist = $newsPostModel->find($id); if ($isExist) { $newsPostModel->delete($id);
} return $this->respond([ ], ResponseInterface::HTTP_OK, ' news post delete it');
}
}
model
PHP Code: <?php namespace App\Models;
use App\Entities\NewsPostEntity; use CodeIgniter\Model;
class NewsPostModal extends Model { protected $table = 'news_post'; protected $primaryKey = 'id'; protected $returnType = NewsPostEntity::class; protected $allowedFields = [ 'sub_category_id', 'category_id', 'picture', 'user_id', 'title_en', 'title_fa', 'body_en', 'body_fa', 'status', 'created_at', 'updated_at', 'deleted_at' ];
protected $useSoftDeletes = false; protected $useTimestamps = true; protected $createdField = 'created_at'; protected $updatedField = 'updated_at'; protected $deletedField = 'deleted_at'; protected $validationRules = [ 'title_fa' => 'required|min_length[3]|max_length[255]', 'title_en' => 'required|min_length[3]|max_length[255]', 'picture' => 'required|min_length[3]|max_length[255]', 'body_en' => 'required', 'body_fa' => 'required', ]; protected $validationMessages = []; protected $skipValidation = false;
}
entity
PHP Code: <?php namespace App\Entities;
use \CodeIgniter\Entity; use CodeIgniter\I18n\Time;
class NewsPostEntity extends Entity {
public function __construct(array $data = null) { parent::__construct($data);
}
protected $id; protected $sub_category_id; protected $category_id; protected $user_id; protected $title_en; protected $picture; protected $title_fa; protected $body_en; protected $body_fa;
protected $status; protected $created_at; protected $updated_at; protected $deleted_at;
protected $attributes = [ 'id' => null, 'sub_category_id' => null, 'category_id' => null, 'user_id' => null, 'title_en' => null, 'title_fa' => null, 'body_en' => null, 'body_fa' => null, 'status' => null, 'picture' => null, 'created_at' => null, 'updated_at' => null, 'deleted_at' => null, ]; protected $datamap = [ ];
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $casts = [ 'status' => 'boolean', ];
protected $permissions = [];
protected $roles = [];
public function disableStatus() { $this->attributes['status'] = 0; return $this;
}
public function enableStatus() { $this->attributes['status'] = 1;
return $this; }
public function isStatus(): bool { return isset($this->attributes['status']) && $this->attributes['status'] == true; }
public function createdAt() {
// date_default_timezone_set('Asia/Tehran'); $this->attributes['created_at'] = date('Y-m-d H:i:s', time()); // $this->attributes['created_at'] = new Time(date('Y-m-d H:i:s', time()), 'UTC'); return $this; }
public function updatedAt() {
// date_default_timezone_set('Asia/Tehran'); $this->attributes['updated_at'] = date('Y-m-d H:i:s', time());
return $this; }
public function initPicture() { $this->attributes['picture'] = 'copy image link here!'; return $this;
}
public function editPicture() {
$this->attributes['picture'] = 'public/upload/news/thumbnail' . $this->attributes['picture'];
return $this; }
}
Unfortunately, I don't see the connection between your posting and my problem ...
But I have solved it:
I set the assignment of the "Foreign Key" in the wrong place. I just had to put it in the other table and just put an index on the column in the reference table.
|