I have a rather weired error on trying to add data to my database. It keeps telling me that there is an Integrity violation, i.e.
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`ticketing_system`.`parcels`, CONSTRAINT `FK_parcels_customers_customer_id` FOREIGN KEY (`sender_id`) REFERENCES `customers` (`customer_id`))
The SQL being executed was: INSERT INTO `parcels` (`parcel_id`) VALUES (DEFAULT)
I have checked the values being inserted and all of them are picked from the referenced table. Funny bit is that when I echo the values and use them to update the database directly via SQL query on the PHPMyAdmin, the database is populated well without any problem. Again, when I try to change the order of the foreign keys as they appear on the SQL query being performed, the first one fails, meaning all the foreign keys of the model are failing.
EDITED
Here is my actionCreate in the ParcelsController
public function actionCreate()
{
$model = new Parcels();
$customerModel = new Customers();
//checking whether we are getting the logged in user id value
Yii::info("User id=".Yii::$app->user->id);
$model->received_by_id = Yii::$app->user->id;
if (Yii::$app->request->post()) {
$data = Yii::$app->request->post('Customers');
$sender_id = Customers::create([
'name' => $data['name'],
'mobile_number' => $data['mobile_number'],
'sex' => $data['sex'],
'address' => $data['address'],
'registered_by_id' => $model->received_by_id,
]);
$data = Yii::$app->request->post('Parcels');
$receiver_id = Customers::create([
'name' => $data['name'],
'mobile_number' => $data['mobile_number'],
'sex' => $data['sex'],
'address' => $data['address'],
'registered_by_id' => $model->received_by_id,
]);
$model->consignment_number = $model->generateUniqueRandomString("consignment_number");
$model->source_id = $model->receivedBy->station_id;
$model->parcel_id = Parcels::create([
'consignment_number' => $model->consignment_number,
'sender_id' => $sender_id,
'receiver_id' => $receiver_id,
'source_id' => $model->source_id,
'destination_id' => $data['destination_id'],
'type_id' => $data['type_id'],
'weight' => $data['weight'],
'cost' => $data['cost'],
'parcel_info' => $data['parcel_info'],
'received_by_id' => $model->received_by_id,
]);
// return $this->redirect(['view', 'id' => $model->parcel_id]);
} else {
return $this->render('create', [
'model' => $model, 'customerModel' => $customerModel,
]);
}
}
Customers::create function in the Customers Model
public static function create($data)
{
$model = new self;
$mobile_number = $data['mobile_number'];
$exists = $model->find()->where( [ 'mobile_number' => $mobile_number ] )->exists();
if($exists) {
$existing_customer = Customers::find()
->where('mobile_number = :mobile_number', [':mobile_number' => $mobile_number])
->one();
return $existing_customer['customer_id'];
}
else {
$model->name = $data['name'];
$model->registered_by_id = $data['registered_by_id'];
$model->mobile_number = $data['mobile_number'];
$model->sex = $data['sex'];
$model->address = $data['address'];
$model->status = 10;
$model->save();
return $model->getPrimaryKey();
}
}
Parcels::create function in the Parcels Model
public static function create($data)
{
$model = new self;
$consignment_number = $data['consignment_number'];
$receiver_id = $data['receiver_id'];
$sender_id = $data['sender_id'];
$source_id = $data['source_id'];
$destination_id = $data['destination_id'];
$type_id = $data['type_id'];
$weight = $data['weight'];
$cost = $data['cost'];
$parcel_info = $data['parcel_info'];
$received_by_id = $data['received_by_id'];
$model->save(false);
return $model->getPrimaryKey();
// echo var_dump($data);
// echo "Consignment Number: ".$consignment_number." - Sender: ".$sender_id." - Receiver: ".$receiver_id." - From: ".$source_id." - To: ".$destination_id." - Type: ".$type_id." - Weight: ".$weight." - Cost: ".$cost." - Parcel Info: ".$parcel_info." - Received By: ".$received_by_id;
}
And here is the function generateUniqueRandomString() in the Parcels Model
public function generateUniqueRandomString($attribute, $length = 10) {
$randomString = Yii::$app->getSecurity()->generateRandomString($length);
$randomString = strtoupper($randomString);
if(!$this->findOne([$attribute => $randomString]))
return $randomString;
else
return $this->generateUniqueRandomString($attribute, $length);
}
Sorry for bothering you guys. I was able to get the problem of where I was going wrong. In the create() function of the Parcels Model, I only created new variables and failed to bind them to the model, i.e.
$consignment_number = $data['consignment_number'];
$receiver_id = $data['receiver_id'];
$sender_id = $data['sender_id'];
$source_id = $data['source_id'];
$destination_id = $data['destination_id'];
$type_id = $data['type_id'];
$weight = $data['weight'];
$cost = $data['cost'];
$parcel_info = $data['parcel_info'];
$received_by_id = $data['received_by_id'];
Should have been:
$model->consignment_number = $data['consignment_number'];
$model->weight = $data['weight'];
$model->cost = $data['cost'];
$model->parcel_info = $data['parcel_info'];
$model->received_by_id = $data['received_by_id'];
$model->status = $data['status'];
$model->receiver_id = $data['receiver_id'];
$model->sender_id = $data['sender_id'];
$model->source_id = $data['source_id'];
$model->destination_id = $data['destination_id'];
$model->type_id = $data['type_id'];
Sorry for taking your time because of my carelessness.
Related
I want to retrieve some data from 'tbl_karyawan' and input into 'tbl_absen' which is if the NIP exist from 'tbl_karyawan' then parshing some data into 'tbl_absen'. I was create the code, and the data is going well. but i have something trouble with
i want the data input in Nip_kyn be like 'KIP001' not [{"Nip_kyn":"KIP001"}].
this is my Model
public function presensi($data)
{
$isExist = DB::table('tbl_karyawan')
->where('Nip_kyn', $data)->exists();
if ($isExist) {
$namakyn = DB::table('tbl_karyawan')->where($data)->get('Nama_kyn');
$nippppp = DB::table('tbl_karyawan')->where($data)->select('Nip_kyn')->get($data);
$values = array('Nip_kyn' => $nippppp, 'Nama_kyn' => $namakyn, 'Jam_msk' => now(), 'Log_date' => today());
DB::table('tbl_absen')->insert($values);
} else {
echo 'data not available';
}
}
this is my controller
public function get()
{
$day = [
'time_in' => $this->AbsenModel->timeIN(),
'time_out' => $this->AbsenModel->timeOut(),
'break' => $this->AbsenModel->break(),
// absen here
's' => $this->AbsenModel->absensi(),
];
$data = [
'Nip_kyn' => Request()->Nip_kyn,
];
$this->AbsenModel->presensi($data);
return view('v_absen', $data, $day);
}
Yup, I finally got it, the problem is on my model.
$nama_karyawan = DB::table('tbl_karyawan')->where($data)->value('Nama_kyn');
$nipkyn = DB::table('tbl_karyawan')->where($data)->value('Nip_kyn');
I just change 'get' to 'value'.
I have 3 tables:
stations (id,station_name)
products (id,product_name)
product_station (station_id,product_id)
Station Model
protected $fillable = ['station_name'];
public function products(){
return $this->belongsToMany(Product::class);
}
Product Model
protected $fillable = ['product_name'];
public function stations(){
return $this->belongsToMany(Station::class);
}
I already have inserted stations and products and i want to insert
station with it's own product using into Pivot table
AdminProductStationcontroller
public function create()
{
$station = Station::pluck('station_name','id')->all();
$products = Product::pluck('product_name','id')->all();
return view('admin.product_stations.create',compact('station','products'));
}
I think there is error in store function below
public function store(Request $request)
{
$station = new Station();
$product = new Product();
$station->save();
$station->products()->attach($product);
return redirect('/admin/product_stations');
}
So i have got this error
(2/2) QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'product_id' cannot be null (SQL: insert into product_station (product_id, station_id) values (, 25))
attach() expects a single or an array of ids of the related Model implying that the Model should have been created beforehand.
What you're looking for is the save(Model) method.
$station->products()->save($product);
More on the above in the docs: https://laravel.com/docs/5.8/eloquent-relationships#updating-many-to-many-relationships
You should firstly save
$station = new Station();
$station->save();
$product = new Product();
$product->save();
then
https://laravel.com/docs/6.x/eloquent-relationships#updating-many-to-many-relationships
$station->products()->attach($product->id);
OR
You can try to save like so
$station->products()->save($product);
// Post Model
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
public function tags()
{
return $this->belongsToMany('App\Tag')->withTimestamps();
}
public function store(Request $request)
{
$this->validate($request,[
'title' =>'required',
'image' => 'mimes:jpeg,jpg,bmp,png',
'categories' => 'required',
'tags' => 'required',
'body' => 'required',
'live_demo' =>'required'
]);
$image = $request->file('image');
$slug = str_slug($request->title);
if (isset($image))
{
$currentDate = Carbon::now()->toDateString();
$imagename = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $image->getClientOriginalExtension();
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(1600,1066);
if (!file_exists('storage/uploads/post'))
{
mkdir('storage/uploads/post',0777,true);
}
//$image->move('storage/uploads/post',$imagename);
$image_resize->save('storage/uploads/post/'.$imagename);
}else{
$imagename = "default.png";
}
$post = new Post();
$post->user_id = Auth::id();
$post->title = $request->title;
$post->slug = str_slug($request->title);
$post->image = $imagename;
$post->body = $request->body;
$post->price = $request->price;
$post->live_demo = $request->live_demo;
if(isset($request->status))
{
$post->status =true;
}else
{
$post->status = false;
}
$post->is_approved = true;
$post->save();
$post->categories()->attach($request->categories);
$post->tags()->attach($request->tags);
Toastr::success('Post Successfully Save:)','Success');
return redirect()->route('admin.post.index');
}
// Pivot table create category_post column create category_id, post_id.
// Pivot table create post_tag, and column create post_id, and tag_id
$station->products()->sync($request->products , false);
I'm trying to make an update with values from a form and pass it into an update controller using a route, there's no error given but why there's nothing happen after I updated the data?
Form:
<form action="/update" id="frm_edit" method="post" enctype="multipart/form-data">
Routes:
Route::post('/update', 'EditManga#update'); //update route
Route::post('/admin_page/manga_list', 'Add_Manga_Controller#upload')->name('upload.image');
Route::get('/admin_page/manga_list','ShowData#Manga_list');
Controller:
public function update(Request $request){
$this->validate($request, [
'image' => 'required|image|mimes:jpg,png,jpeg'
]);
//MENGAMBIL FILE IMAGE DARI FORM
$kode_manga = $request->input('kdmanga');
$judul = $request->input('jdmanga');
$alternatif = $request->input('almanga');
$author = $request->input('aumanga');
$status = $request->status;
$lastup = $request->input('lumanga');
$genre = $request->input('grmanga');
$lastc = $request->input('lcmanga');
$sinopsis = $request->input('sinopsis');
$file = $request->file('image');
DB::table('add_manga')->where('kode_manga',$kode_manga)->update([
'judul_manga' => $judul,
'alt_title' => $alternatif,
'author' => $author,
'status' => $status,
'uploaded' => $lastup,
'genre' => $genre,
'latest' => $lastc,
'summary' => $sinopsis
]);
return redirect('/admin_page/manga_list');
}
}
is there any other way or there something's wrong with my code?, Thank you.
In you scenario this another of doing this:
public function update(Request $request, $id)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpg,png,jpeg'
]);
//MENGAMBIL FILE IMAGE DARI FORM
$kode_manga = $request->input('kdmanga');
//getting the target row to updae
$addmanga = DB::table('add_manga')->select('*')
->where('kode_manga',$kode_manga)->get();
$id = $addmanga->id; // getting the id of the target
$add_manga = App\YOUR_MODEL_NAME::find($id);
$add_manga->judul_manga = $request->input('jdmanga');
$add_manga->alt_title = $request->input('almanga');
$add_manga->author = $request->input('aumanga');
$add_manga->status = $request->status;
$add_manga->uploaded = $request->input('lumanga');
$add_manga->genre = $request->input('grmanga');
$add_manga->latest = $request->input('lcmanga');
$add_manga->summary = $request->input('sinopsis');
$add_manga->file = $request->file('image');
$add_manga->save();
return redirect('/admin_page/manga_list');
}
Hope this will work for you!
I am new to cakephp.Below the number being bold is the time the data is being created and code to validate .My problem is to validate the data should between 8 hours not more that using Model. is there any wrong in my code?
sample data=L02A-180129-1215-A
The code to find the table based on data
public function sa01() {
$trv_no = $this->data[$this->alias]['TRV_No_01'];
$line_no = intval(substr($trv_no, 1, 2));
$table_name = 'Ticket_L' . $line_no;
$this->Ticket->setSource($table_name);
$this->Ticket->recursive =-1;
code for validation
Batch_time is a column name for the table
$time = $this->Ticket->find('all',array('conditions' => array('Ticket.Batch_Time >=' => date('Y-m-d H:i:s', strtotime('-8 hour')))));
if(empty($time))
{
$table_name = 'Ticket_L0';
$this->Ticket->setSource($table_name);
//$ticket = $this->Ticket->find('first', array('conditions' => array('Ticket.TRV_No' => $trv_no)));
$time = $this->Ticket->find('all',array('conditions' => array('Ticket.Batch_Time >=' => date('Y-m-d H:i:s', strtotime('-8 hour')))));
if(empty($time)) { return false; } else { return true; }
}
else
{ return true; }
}
I am trying to create shipment and adding tracking number after placing an order,but i am getting an error like Cannot create an empty shipment. when i search through google i got one of the reason for this is item quantity is null, but what i used below is returning the exact quantities of products ordered.
$itemQty = $order->getItemsCollection()->count();
I don't know exactly it is only the reason for that error. what i done mistake? anybody knows please help me on this.
public function salesOrderInvoiceShipmentCreate($observer)
{
// $order = $observer->getEvent()->getOrder();
//$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
$order_id = $observer->getData('order_ids');
$order = Mage::getModel('sales/order')->load($order_id);
$token = '3acb6561b04117c6cbe3552c90f1d6815507e257';
$waybill_url = 'https://track.delhivery.com/waybill/api/fetch/json/?token='.$token.'&cl=GEECHOO';
$waybill = file_get_contents($waybill_url);
Mage::log($order, Zend_Log::INFO, 'order.log', true);
if (!$order->getId()) {
Mage::throwException('Order does not exist, for the Shipment process to complete');
}
if ($order->canShip()) {
try {
// $shipment = Mage::getModel('sales/service_order', $order)
// ->prepareShipment($this->_getItemQtys($order));
$itemQty = $order->getItemsCollection()->count();
$shipment = Mage::getModel('sales/service_order', $order)->prepareShipment($itemQty);
$shipmentCarrierCode = '';
$shipmentCarrierTitle = '';
$arrTracking = array(
'carrier_code' => isset($shipmentCarrierCode) ? $shipmentCarrierCode : $order->getShippingCarrier()->getCarrierCode(),
'title' => isset($shipmentCarrierTitle) ? $shipmentCarrierTitle : $order->getShippingCarrier()->getConfigData('title'),
'tracking_number' => $waybill,
);
$track = Mage::getModel('sales/order_shipment_track')->addData($arrTracking);
$shipment->addTrack($track);
// Register Shipment
$shipment->register();
// Save the Shipment
$this->_saveShipment($shipment, $order);
// Finally, Save the Order
$this->_saveOrder($order);
} catch (Exception $e) {
throw $e;
}
}
}
Try this for order item quantity
$quote = Mage::helper('checkout/cart')->getCart()->getQuote();
$value = [];
foreach ($quote->getAllItems() as $item) {
$value[]= array (
'id' => $item->getSku(),
'quantity' => $item->getQty(),
}