code igniter delete data from different model using single query - codeigniter

[i want to delete data from two table using two models but cant do . am using following code .help me to fix this problem]
public function delete_all_info_employee($id) {
// ************* Delete into Employee Table
$this->employee_model->_table_name = "tbl_employee"; // table name
$this->employee_model->_primary_key = "employee_id"; // $id
$this->employee_model->delete($id);
$this->expense_model->_table_name = "tbl_expense"; // table name
$this->expense_model->_primary_key = "expense_id"; // $id
$this->expense_model->delete($id);
$type = "success";}

1st check you already loaded database in codeigniter\application\config\autoload.php
$autoload['libraries'] = array('database');
your method of model
public function delete_all_info_employee($id) {
// ************* Delete into Employee Table
$this->db->where('employee_id', $id);
$this->db->delete('tbl_employee');
$this->db->where('expense_id', $id);
$this->db->delete('tbl_expense');
return "success";
}

Related

Using Laravel query builder , I need rejected bids from two table order and bids

I have two tables in my database, one is order and second one is named as bids. As the name suggests, I am storing all the jobs in the order table and Whenever someone's bids for the particular job, I am storing their bid information in bids table.
whenever client accept job acceptedBidId sotres bidid which is same as bid id in order table.
I am having troubles in fetching rejected bids for specific user, where we have a condition that all those bids which are assigned to some other users are
I am not able to write query in Laravel using Laravel query builder.
$user = Auth::user();
$user_id = $user->id;
$status = $request->input('status');
$order_direction = $request->has('order_direction') ? $request->input('order_direction') : 'desc';
$order_by = $request->has('order_by') ? $request->input('order_by') : 'id';
$per_page = $request->has('limit') ? $request->input('limit') : 15;
$query = Bid::query();
$query->whereHas('order', function($q) { $q->orWhereNotNull('acceptedBidId'); })
->where('user_id',$user_id);
if(!empty($status)) {
$query->where('status',$status);
}
if(!empty($order_by) && !empty($order_direction)) {
$query->orderBy($order_by,$order_direction);
}
$bids = $query->paginate($per_page);
return response()->success($bids);
I need all the rejected bids for the particular user.enter image description here
enter image description here
Assuming you have the following model relation
// Model
class Bid extends Model
{
public function order()
{
return $this->hasOne(Order::class);
}
}
Then you should include a condition to check for the rejected one like this:
// Query builder
if($isRejected) {
$query->doesntHave('order');
}

Why can't laravel/eloquent find certain table?

I'm trying to fetch some data from a table called "category", but laravel is throwing the
"SQLSTATE[42S02]: Base table or view not found" error.
I've tried with other table names like "company" and it works perfectly. Both of these tables exist but one of them can not be found with the same code.
This throws the error:
public static function getCategories()
{
$categories = [];
$cat = DB::table('category')->get();
if (isset($cat)){
foreach ($cat as $category_name){
array_push($categories, $category_name);
}
return json_encode($categories);
}
return null;
}
This works as expected (same code except for the table name string):
public static function getCategories()
{
$categories = [];
$cat = DB::table('company')->get(); //table name changed
if (isset($cat)){
foreach ($cat as $category_name){
array_push($categories, $category_name);
}
return json_encode($categories);
}
return null;
}
The only difference between those two tables is table collation:
company: utf8_general_ci
category: utf8mb4_swedish_ci
Create a model if it you don't have one. Add the following into your category model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'category';
}
Controller
public static function getCategories()
{
$categories = [];
$cat = Category::all();
if (isset($cat)){
foreach ($cat as $category_name){
array_push($categories, $category_name);
}
return json_encode($categories);
}
return null;
}
You're currently using Query Builder, try use eloquent way.
Ok, I found out we had two separate database-servers with almost identical data in them. Both had databases and tables with the same names, but one was missing the category table.
Of course I was connected to the wrong server from laravel after all.
TL;DR: Simple user error in configuration.

Laravel: How to update pivot tables withou using first

Im new in Laravel. I want to update my leaves pivot table. I am trying with below code but it only updates the single row i have multiple rows in db with same leave_id and i want to update all this where leave_id = xyz
I have following function in my model Leave:
public function relLeave(){
return $this->belongsToMany(User::class)->withPivot('days');
}
LeaveController:
public function saveUpdate(Request $request)
{
$leave = Leave::find($request->id);
$msg = $leave->relLeave()->Where('leave_id', $request->id)->get()->first();
$msg->pivot->days = $request->days;
$msg->pivot->save();
}
I followed #option's instruction and it works for me i removed the first();
below is my updated code.
$msg = $leave->relLeave()->Where('leave_id', $request->id)->get();
foreach($msg as $msgs)
{
$msgs->pivot->days = $request->days;
$msgs->pivot->save();
}
you can update extra fields in pivot table when updating relationship
$leave->relLeave()->sync([$request['id'] => ['days' => $request['days']]]);
You can use Query Builder for that if it's an option:
DB::table('leave_user')->where('leave_id', $request->id)->update(['days' => $request->days]);
This is just one DB query and it's pretty simple one.
If you want Eloquent solution, use updateExistingPivot() in a loop:
$leave = Leave::find($request->id);
$usersIds = $leave->relLeave()->pluck('id')->toArray();
foreach ($usersIds as $userId) {
$leave->relLeave()->updateExistingPivot($userId, ['days' => $request->days]);
}

How does loadByCode() works in magento

How does loadByCode() works? I have been adding a module to my new project and don't know how to use model uses loadByCode method with a given code.
When you look at magento model class it extends Mage_Core_Model_Abstract which intern extends Varien_Object.
The class Mage_Core_Model_Abstract has function like getId(), load(), save(), delete() etc...
Mysql4 resource files are used to perform database queries on tables.
Suppose we have the file Keyur_Test_Model_Mysql4_Test resource file.
<?php
class Keyur_Test_Model_Mysql4_Test extends Mage_Core_Model_Mysql4_Abstract
{
public function _construct()
{
$this->_init('test/test', 'test_id');
}
public function loadByField($field,$value){
$table = $this->getMainTable();
$where = $this->_getReadAdapter()->quoteInto("$field = ?", $value);
$select = $this->_getReadAdapter()->select()->from($table,array('test_id'))->where($where);
$id = $this->_getReadAdapter()->fetchOne($sql);
return $id;
}
}
And here is the model file Keyur_Test_Model_Test
<?php
class Keyur_Test_Model_Test extends Mage_Core_Model_Abstract
{
public function _construct()
{
parent::_construct();
$this->_init('test/test');
}
public function loadByField($field,$value){
$id = $this->getResource()->loadByField($field,$value);
$this->load($id);
}
}
In this file there are many new functions which have been used. Let’s take them one by one. In our model file, we have used this function -
$id = $this->getResource()->loadByField($field,$value);
$this->getResource() function returns the resource model’s object. So we are simply calling the loadyByField($field,$value) function in the resource model.
getTable() function
Now in our Mysql4 file, in the loadByField() function we have used $table = $this->getMainTable(); .This function returns the table name of the current model, i.e the one defined in the class’s constructor. If you want to get table name of another sql table in magento, we need to the getTable() call e.g
$table = $this->getTable(‘newsletter/subscribe’);
_getReadAdapter() function
Next we have:
$where = $this->_getReadAdapter()->quoteInto(“$field = ?”, $value);
Here the first function too see is the $this->_getReadAdapter() function. This function return an object which has function to perform database query, like fetch(), fetchAll(), query(), etc.
_quoteInfo() function
Another function we have used is quoteInto(): This function is used to create our where conditions.
In this the actual value is substituted into the question mark we have written. For e.g $this->_getReadAdapter()->quoteInto(“user_id = ?”, 3); translates to “user_id = 3″.
Another frequently used variation of quoteInfo() is
$where = $this->_getReadAdapter()->quoteInto("$field IN(?)", array(1,2,3));
this translates to “field in (1,2,3)”
Getting deeper into the quoteInto() function: If we have multiple where conditions we can use
$where = $this->_getReadAdapter()->quoteInto("$field = ? AND ", $value).$this->_getReadAdapter()->quoteInto("$field1 = ? OR ", $value1).$this->_getReadAdapter()->quoteInto("$field2 = ?", $value2);
Continuing on the loadByField function in our resource model, next we have
$select = $this->_getReadAdapter()->select()->from($table,array(‘test_id’))->where($where);
Here we have created the select query using the select(), and on that called the from() function.
from() function
The from() function takes many different parameters, if you want to fire a simple select * query, you need to only pass the table name like from($table).
But right now, I wanted to select just a single column that is test_id, so I passed an array with column name to
select. i.e array(‘test_id’).
If we want to select multiple column, we need to array(‘test_id’,’col1’,’col2’).
This will create a sql like “select test_id,col1,col2 from $table”.
But support we want a sql query like “select test_id as id,col1 as column1 from $table” , i would call -
from($table,array('id'=>'test_id','column1'=>'col1'));

How to update field when delete a row in laravel

Let I have a table named customer where customer table has a field named deleted_by.
I implement softDelete in customer model. Now I want to update deleted_by when row delete. So that I can trace who delete this row.
I do search on google about it But I don't found anything.
I use laravel 4.2.8 & Eloquent
You may update the field using something like this:
$customer = Customer::find(1); // Assume 1 is the customer id
if($customer->delete()) { // If softdeleted
DB::table('customer')->where('id', $customer->id)
->update(array('deleted_by' => 'SomeNameOrUserID'));
}
Also, you may do it in one query:
// Assumed you have passed the id to the method in $id
$ts = Carbon\Carbon::now()->toDateTimeString();
$data = array('deleted_at' => $ts, 'deleted_by' => Auth::user()->id);
DB::table('customer')->where('id', $id)->update($data);
Both is done within one query, softDelete and recorded deleted_by as well.
Something like this is the way to go:
// override soft deleting trait method on the model, base model
// or new trait - whatever suits you
protected function runSoftDelete()
{
$query = $this->newQuery()->where($this->getKeyName(), $this->getKey());
$this->{$this->getDeletedAtColumn()} = $time = $this->freshTimestamp();
$deleted_by = (Auth::id()) ?: null;
$query->update(array(
$this->getDeletedAtColumn() => $this->fromDateTime($time),
'deleted_by' => $deleted_by
));
}
Then all you need is:
$someModel->delete();
and it's done.
I would rather use a Model Event for this.
<?php
class Customer extends \Eloquent {
...
public static function boot() {
parent::boot();
// We set the deleted_by attribute before deleted event so we doesn't get an error if Customer was deleted by force (without soft delete).
static::deleting(function($model){
$model->deleted_by = Auth::user()->id;
$model->save();
});
}
...
}
Then you just delete it like you would normally do.
Customer::find(1)->delete();
I know this is an old question, but what you could do (in the customer model) is the following....
public function delete()
{
$this->deleted_by = auth()->user()->getKey();
$this->save();
return parent::delete();
}
That would still allow the soft delete while setting another value just before it deletes.

Resources