In model there is two fuctions
public function getItemsOrder(){
return $this->hasMany(OrderItems::className(), ['order_id' => 'order_id']);
}
public function getOrderInfo(){
return $this->hasMany(OrderItemsOffer::className(), ['order_items_id' => 'order_items_id'])
->viaTable('order_items', ['order_id' => 'order_id']);
}`
Table orderhas order_id, table order_items has order_id and order_items_id, table order_items_offer has order_items_id and order_items_offer_name. One order_id can have many order_items_id. Table order_items also has order_items_quantity.
I can get quantity of order_items with first function. And name of all order_items with second function, like this
[
'value' => function ($data) {
$summ = 0;
$str = 0;
foreach($data->itemsOrder as $request) {
$str .= $request->order_items_quantity;
$summ += $str;
}
return $summ;
},
],
['value' => function($data){
$sum = '';
foreach ($data->orderInfo as $request){
$str = ($request->order_items_offer_name);
$sum .= $str.',';
}
return $sum ;
}],
How could I get this data in one column, like 'FirstItem 2 piece, SecondItem 3 piece'?
Maybe someone helps, create in OrderItems
public function getOrderInfo(){
return $this->hasOne(OrderItemsOffer::className(), ['order_items_id' => 'order_items_id']);
}
In view
[
'value' => function ($data) {
$summ = 0;
$str = '';
foreach($data->itemsOrder as $request) {
$summ = $request->order_items_quantity;
$str .= (strlen($str))?', ': '';
$str .= $request->orderInfo->order_items_offer_name.' '.$summ.'шт.';
}
return $str;
},
],
Related
Error Image
Working on a Multi vendor website . Suddenly got this error when shop/vendor user want to login no problem normal user Here two type user one is vendor or ShopOwner/ another one normal Customer when vendor want to logging got this error. But normal user no Problem facing for login. Added new column but problem is continue SQL integrity Error.
Query: (SQL: select * from `shops` where `user_shops` = 233 limit 1)
Here is Login Controller.
Details for Login Controller
public function userlogin(Request $request){
$data = Cart::getContent();
$this->validate($request, [
'email' => 'required',
'password' => 'required',
],[
'email.required' => 'Email not matched with Database!',
'password.required' => 'Password not matched with Database!',
]);
$checkUserInput = filter_var($request->input('email'), FILTER_VALIDATE_EMAIL)?'email': 'username';
$user = Auth::guard('web')->attempt([$checkUserInput => $request->email,'password'=>$request->password]);
if($user == 'true'){
if(Auth::user()->is_activated == 1){
if(count($data)>0){
if(count(Cart::session(Auth::user()->id)->getContent())>0){
foreach ($data as $key => $value) {
if(!Cart::session(Auth::user()->id)->get($value->id) ){
Cart::session(Auth::user()->id)->add($value->id, $value->name,$value->price,$value->quantity, $value->image,array('color' => $value->attributes->color));
}else{
Cart::session(Auth::user()->id)->update($value->id, array(
'quantity' => array(
'relative' => false,
'value' => $request->quantity
),
'attributes' => array(
'color' => $value->attributes->color
),
));
}
}
}else{
foreach ($data as $key => $value) {
Cart::session(Auth::user()->id)->add($value->id, $value->name,$value->price,$value->quantity, $value->image,array('color' => $value->attributes->color));
}
}
}
if(Auth::user()->user_type == 2){
$model = Shop::where('user_id',Auth::user()->$user_id)->first();
if($model){
if($request->previous){
return redirect()->route('neneMart.dashboard');
}else{
return Redirect::to($request->previous);
}
}else{
if(empty($request->previous)){
return redirect()->route('create-shop');
}else{
return Redirect::to($request->previous);
}
}
}else{
if(empty($request->previous)){
return redirect()->route('home');
}else{
return Redirect::to($request->previous);
}
}
}
else{
return redirect()->route('user-login')->with(Auth::logout())->with('error', 'User email has not been activated yet!');
}
}else{
return redirect()->route('user-login')->with('error', 'Whoops! Wrong Email or Username or Password !');
}
}`
ROUTE
Route:: get('user-login', 'Auth\LoginController#usershowLoginForm')->name('user-login');
Route:: post('userLogin', 'Auth\LoginController#userlogin')->name('userLogin');
Shop Management Controller
public function index()
{
$shop = Shop::where('user_id',Auth::user()->id)->first();
$model = ShopManagement::where('shop_id','Nenemart-'.$shop->id)->first();
$shopid = 'Nenemart-'.$shop->id;
$agent = new Agent();
if($agent->isMobile() || $agent->isTablet()){
return view('mobile.mart.shopmanagemnt',compact('model','shopid'));
}else{
return view('frontend.mart.shopmanagemnt',compact('model','shopid'));
}
}
public function vendorShop(){
$shop = Shop::where('user_id',Auth::user()->id)->first();
$model = ShopManagement::where('shop_id','Nenemart-'.$shop->id)->first();
$vendorProducts = Product::orderBy('id', 'dese')->where('created_by', $shop->id)->where('type', 1)->get();
$agent = new Agent();
if($agent->isMobile() || $agent->isTablet()){
return view('mobile.mart.vendorShop',compact('model', 'vendorProducts'));
}else{
return view('frontend.mart.vendorShop',compact('model', 'vendorProducts'));
}
}
ShopManagement Model
protected $table = 'shop_management';
protected $primaryKey = 'id';
public static function getImage($shop_id){
$model = Self::where('shop_id','Nenemart-'.$shop_id)->first();
if($model){
return $model->shop_logo;
}else{
return '';
}
}
}
**Shop Model **
<?php
namespace App\Model\Frontend;
use Illuminate\Database\Eloquent\Model;
use Session;
use App\Model\Product;
use App\Model\MobileColor;
use App\Http\Controllers\HomeController;
use Auth;
use DB;
class Shop extends Model
{
protected $fillable = [
'user_id', 'shop_name', 'complex_name', 'brand_category_id', 'shop_mobile', 'shop_phone', 'trade_license', 'address', 'city', 'zipcode', 'opening_day', 'opening_time', 'closing_time'
];
public static function checkShopIsVerified($user_id){
$model = Self::where('user_id',$user_id)->where('status',1)->first();
if($model){
return true;
}else{
return false;
}
}
public static function getTodayOrder(){
$shop = Shop::where('user_id',Auth::user()->id)->first();
if($shop){
$data = DB::select("SELECT po.*, pod.id as pod_id,pod.product_id,pod.color_id,pod.quantity,pod.price,pod.status as p_status,p.product_code,p.model,p.type FROM product_order as po RIGHT JOIN product_order_details as pod ON po.id = pod.order_id JOIN products as p on p.id = pod.product_id WHERE p.created_by = ".$shop->id." and p.type = 1 and pod.status = 0 and po.date=".date('Y-m-d')." order by po.id desc");
$array = Self::processData($data);
}else{
$array = array();
}
return sizeof($array);
}
public static function getTotalCompleteOrder(){
$shop = Shop::where('user_id',Auth::user()->id)->first();
if($shop){
$data = DB::select("SELECT po.*, pod.id as pod_id,pod.product_id,pod.color_id,pod.quantity,pod.price,pod.status as p_status,p.product_code,p.model,p.type FROM product_order as po RIGHT JOIN product_order_details as pod ON po.id = pod.order_id JOIN products as p on p.id = pod.product_id WHERE p.created_by = ".$shop->id." and p.type = 1 and pod.status = 1 order by po.id desc");
$array = Self::processData($data);
}else{
$array = array();
}
return sizeof($array);
}
public static function getTotalPendingOrder(){
$data = DB::select("SELECT po.*, pod.id as pod_id,pod.product_id,pod.color_id,pod.quantity,pod.price,pod.status as p_status,p.product_code,p.model,p.type FROM product_order as po RIGHT JOIN product_order_details as pod ON po.id = pod.order_id JOIN products as p on p.id = pod.product_id WHERE p.type = 1 and pod.status = 0 order by po.id desc");
$array = Self::processData($data);
return sizeof($array);
}
public static function getmonthlySale(){
$first_day_this_month = date('Y-m-01'); // hard-coded '01' for first day
$last_day_this_month = date('Y-m-t');
$total = 0;
$shop = Shop::where('user_id',Auth::user()->id)->first();
if($shop){
$data = DB::select("SELECT pod.quantity*pod.price as total FROM product_order as po RIGHT JOIN product_order_details as pod ON po.id = pod.order_id JOIN products as p on p.id = pod.product_id WHERE p.created_by = ".$shop->id." and p.type = 1 and pod.status = 1 and po.date between ".$first_day_this_month." and ".$last_day_this_month." order by po.id desc");
if(sizeof($data)>0){
foreach($data as $d){
$total +=$d->total;
}
}
}
return $total;
}
Error
add 'user_shops' to fillable model
exam:
protected $fillable = ['user_shops'];
or check if exists 'user_shops' in model?
I am getting data back from a database query but I need to update an array.
sub get_query_data{
my ($self, $user_id) = #_;
my $sql_query = "Select * from table";
my ( $returndata ) = $self->_exec_and_fetch_all( $sql );
for ( #$returndata ) {
push( #$_, 'replace me' );
}
return $returndata;
}
How do I replace the third element when I am looping through the data?
There is data coming back from the query but he above is not working.
If $self->_exec_and_fetch_all can return undef,
my $rows = $self->_exec_and_fetch_all($sql);
if ($rows) {
for my $row (#$rows) {
$row->[2] = 'replaceme';
}
}
return $rows;
Otherwise,
my $rows = $self->_exec_and_fetch_all($sql);
for my $row (#$rows) {
$row->[2] = 'replaceme';
}
return $rows;
or
my $rows = $self->_exec_and_fetch_all($sql);
$_->[2] = 'replaceme' for #$rows;
return $rows;
Here customer A and Customer B message to one supplier, suppliers click the Customer A messages and wants to open only the particular customer A's messages not mix both of them. But I am getting the output with both messages from Customer A and Customer B. Please help me to solve this.
Model
[public function customer_to_supply() {
$this->db->select('*');
$this->db->from('communication');
$this->db->join('supplier_otherdetails', 'supplier_otherdetails.supplierid_fk = communication.supplier_id');
$this->db->join('customer_registration', 'communication.Customer_id=customer_registration.id');
//$this->db->join('communication', 'communication.product_id=contact_supplier.product_id');
$where = "communication.From' =>'customer'";
$this->db->where($where);
$query = $this->db->get();
$results = \[\];
if ($query->num_rows() > 0) {
$results = $query->result();
}
return $results;
}
controller
public function supplier_communication() {
$supp_id = $this->input->post('suppid');
$product_id = $this->input->post('proid');
$cust_id = $this->input->post('custid');
$this->session->userdata('cust',$cust_id);
$result1 = $this->Profile_model->fetch_Data($product_id);
$Userid = $this->session->userdata('id');
$result3 = $this->session->userdata('tt');
$data3 = array(
'message' => $this->input->post('messagee'),
'supplier_id' => $supp_id,
'product_id' => $product_id,
'Customer_id' => $cust_id,
'From' => $result3,
);
$this->Profile_model->data_insertt($data3);
redirect('welcome/messageview');
}
You have to pass the id of the customer ($customer_id) to your model function. Below is your function redesigned:
public function customer_to_supply($customerId) {
$qry = $this->db->select('*')
->from('communication')
->join('supplier_otherdetails', 'supplier_otherdetails.supplierid_fk = communication.supplier_id')
->join('customer_registration', 'communication.Customer_id=customer_registration.id')
->where('communication.From', 'customer')
->where('communication.Customer_id', $customerId)
->get();
if ($qry->num_rows() > 0)
return $qry->result_array();
return FALSE;
}
Hi I am using codeigniter.I need to get the last inserted id and increment it and use it in my view page,
My controller code:
public function add_tickets()
{
$status = $this->input->post("status_button");
$emp_array = $this->input->post("employee");
$start_array = $this->input->post("start_time");
$pid_array = $this->input->post("pid");
$total_array = $this->input->post("total");
if($status == "leave_open")
{
$button_status="open";
}
else
{
$button_status="";
}
$insert_id = $this->billing_model->store_bill($data_to_store);
/*Here I am tring to get the last inserted id*/
for ($i = 0; $i < count($pid_array); $i++) {
if(isset($pid_array[$i])&& $pid_array[$i]!=""){
$data_to_store = array(
'id' => $insert_id +1,
'employee' => $emp_array[$i],
'start_time' => $start_array[$i],
'pid' => $pid_array[$i],
'total' => $total_array[$i],
'status' => $button_status,
);
$this->billing_model->store_bill($data_to_store);
}
}
$data['ticket_new_id'] = $data_to_store['id'];
$data['bill']=$this->billing_model->get_bill();
$data['main_content'] = 'admin/billing/list';
$this->load->view('includes/template', $data);
}
This is my controller function where I insert my bill.
Here is my model function,
function store_bill($data)
{
$insert = $this->db->insert('bill', $data);
$insert_id = $this->db->insert_id();
return $insert_id;
}
Here I am using $this->db->insert_id() to get the last inserted id.
I am getting a error like this,
You must use the "set" method to update an entry.
Filename: C:\xampp\htdocs\elfanto\elfanto_billing\system\database\DB_active_rec.php
Line Number: 1174
Can someone help me? Thanks in advance
I think this is your solution:
<?php
public function add_tickets()
{
$status = $this->input->post("status_button");
$emp_array = $this->input->post("employee");
$start_array = $this->input->post("start_time");
$pid_array = $this->input->post("pid");
$total_array = $this->input->post("total");
if($status == "leave_open")
{
$button_status="open";
}
else
{
$button_status="";
}
/*beore inserting first get the last ID of the table*/
$this->db->select('*');
$this->db->from('bill');
$this->db->order_by('id','desc');
$result = $this->db->get()->result();
$last_id = $result[0]->id;//This is the last ID of the table
/*now insert the data with incremented ID and send it to your view */
$data_to_store = array(
'id' => $insert_id +1,
'employee' => $emp_array,
'start_time' => $start_array,
'pid' => $pid_array,
'total' => $total_array,
'status' => $button_status,
);
$this->billing_model->store_bill($data_to_store);
$insert_id = $last_id + 1;//this will be your last inserted ID
$data['ticket_new_id'] = $insert_id ;
$data['bill']=$this->billing_model->get_bill();
$data['main_content'] = 'admin/billing/list';
$this->load->view('includes/template', $data);
}
For more reference how to get last ID using codeigniter check this
I have check your code not initialize the variable
$status = $this->input->post("status_button");
$emp_array = $this->input->post("employee");
$start_array = $this->input->post("start_time");
$pid_array = $this->input->post("pid");
$total_array = $this->input->post("total");
if($status == "leave_open")
{
$button_status="open";
}
else
{
$button_status="";
}
// $data_to_store is not initialized and you are trying to store the value that's why it give you error
$insert_id = $this->billing_model->store_bill($data_to_store);
Is it possible to predict the operations that follow a DELETE CASCADE automatically? In my software I would like to give the user a warning with details about the data that would be deleted then.
You can make a copy of the database and put triggers on the after delete
DELIMITER $$
CREATE TRIGGER ad_table1_each AFTER DELETE ON table1 FOR EACH ROW
BEGIN
INSERT INTO log VALUES (null /*autoinc id*/
, 'table1' /*tablename*/
, old.id /*tableid*/
, concat_ws(',',old.field1,old.field2 /*CSV's of fields*/
, NOW() /*timestamp*/
, 'delete'); /*what action*/
REPLACE INTO restore_table1 VALUES (old.id,
, old.field1
, old.field2
, ... );
END $$
DELIMITER ;
The log table is just a table with the following fields:
id integer autoincrement primary key
tablename varchar(45)
table_id integer
fields varchar(6000)
delete_time timestamp
action enum('insert','update','delete')
If you do a SELECT #last_id:= max(id) FROM log before the delete cascade on the copy.
Then you can do a SELECT * FROM log WHERE id > #last_id
and get all the rows that will be deleted in the cascade.
After that you can use the restore_table1 to recreate the rows that were deleted in the cascade in the copy database.
I think you could use Johan's trigger solution in combination with a transaction that you roll back. This avoids both the need for a second database and for the manual restore of the deleted entries.
add the trigger and the log table
for each attempted deletion start a transaction and delete the entries
present the information from the log to your user for approval
if the user agrees commit the transaction, otherwise rollback
I wrote a very quick hack that does exactly what you need in PHP, since I wanted to do the exact same thing and haven't found any resources for that online.
It might be too late for you, but it may help others.
function get_referencing_foreign_keys ($database, $table) {
$query = 'SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = "'.$database.'" AND REFERENCED_TABLE_NAME = '.esc($table);
$result = rquery($query);
$foreign_keys = array();
while ($row = mysql_fetch_row($result)) {
$foreign_keys[] = array('database' => $row[0], 'table' => $row[1], 'column' => $row[2], 'reference_column' => $row[3]);
}
return $foreign_keys;
}
function get_foreign_key_deleted_data_html ($database, $table, $where) {
$data = get_foreign_key_deleted_data ($database, $table, $where);
$html = '';
foreach ($data as $key => $this_data) {
$html .= "<h2>$key</h2>\n";
$html .= "<table>\n";
$i = 0;
foreach ($this_data as $value) {
if($i == 0) {
$html .= "\t<tr>\n";
foreach ($value as $column => $column_value) {
$html .= "\t\t<th>".htmlentities($column)."</th>\n";
}
$html .= "\t</tr>\n";
}
$html .= "\t<tr>\n";
foreach ($value as $column => $column_value) {
$html .= "\t\t<td>".htmlentities($column_value)."</td>\n";
}
$html .= "\t</tr>\n";
$i++;
}
$html .= "</table>\n";
}
return $html;
}
function get_foreign_key_deleted_data ($database, $table, $where) {
$GLOBALS['get_data_that_would_be_deleted'] = array();
$data = get_data_that_would_be_deleted($database, $table, $where);
$GLOBALS['get_data_that_would_be_deleted'] = array();
return $data;
}
function get_data_that_would_be_deleted ($database, $table, $where, $recursion = 100) {
if($recursion <= 0) {
die("Deep recursion!");
}
if($recursion == 100) {
$GLOBALS['get_data_that_would_be_deleted'] = array();
}
if($table) {
if(is_array($where)) {
$foreign_keys = get_referencing_foreign_keys($database, $table);
$data = array();
$query = 'SELECT * FROM `'.$table.'`';
if(count($where)) {
$query .= ' WHERE 1';
foreach ($where as $name => $value) {
$query .= " AND `$name` = ".esc($value);
}
}
$result = rquery($query);
$to_check = array();
while ($row = mysql_fetch_row($result)) {
$new_row = array();
$i = 0;
foreach ($row as $this_row) {
$field_info = mysql_fetch_field($result, $i);
$new_row[$field_info->name] = $this_row;
foreach ($foreign_keys as $this_foreign_key) {
if($this_foreign_key['reference_column'] == $field_info->name) {
$to_check[] = array('value' => $this_row, 'foreign_key' => array('table' => $this_foreign_key['table'], 'column' => $this_foreign_key['column'], 'database' => $this_foreign_key['database']));
}
}
$i++;
}
$GLOBALS['get_data_that_would_be_deleted'][$table][] = $new_row;
}
foreach ($to_check as $this_to_check) {
if(isset($this_to_check['value']) && !is_null($this_to_check['value'])) {
get_data_that_would_be_deleted($database, $this_to_check['foreign_key']['table'], array($this_to_check['foreign_key']['column'] => $this_to_check['value']), $recursion - 1);;
}
}
$data = $GLOBALS['get_data_that_would_be_deleted'];
return $data;
} else {
die("\$where needs to be an array with column_name => value pairs");
}
} else {
die("\$table was not defined!");
}
}
Imagine I have a table called "table" in the database "db" and I want to delete the one with the id 180, then I'd call:
print(get_foreign_key_deleted_data_html('db', 'table', array('id' => 180)));
and it prints a full table with all the rows and all the values that would be deleted.
But as I've said, this is a very, very quick and dirty hack. I'd be glad for any bug-report (and there surely are a lot of them!).