how to update query in CI - codeigniter

i have update query problem in codeigniter.
$arrPartnerId = $partnerData['partner_id'];
print_r($partnerData['partner_id']);
if(is_array($arrPartnerId) > 0 ){
foreach( $arrPartnerId as $partnerId){
$this->db->set('partner_id', $partnerId );
$this->db->where('promotion_id', $promotionData['promotion_id'] );
$this->db->update('partner_promotion_relation');
}
}
my data is $aaPartnerId=([0]=>4,[1]=>5) and i have one id then how to update in database.

I think you confuse a where and set condition, you should rather have this :
$this->db->set('promotion_id', $promotionData['promotion_id']);
$this->db->where('partner_id', $partnerId);
$this->db->update('partner_promotion_relation');
It's just a hypothesis, because in your case you keep update 2 times the same line in your table, which is not logical.

If your array is like this,
$arrPartnerId = array(
0 => 4,
1 => 5
);
And
$promotionData['promotion_id'] = 123; //assumption
Then try this,
if(sizeof($arrPartnerId) > 0 )
{
foreach( $arrPartnerId as $partnerId)
{
$this->db->set('partner_id', $partnerId );
$this->db->where('promotion_id', $promotionData['promotion_id'] );
$this->db->update('partner_promotion_relation');
}
}
It will resolve the problem.

Related

how to exchange data in laravel

I have the table structure below
how so that, if processed with the button, id_modul can change
id id_level id_modul
1 1 1
2 1 3
3 1 2
please, help me!
You can do something like this:
$module = Module::where('id_level', 1)->where('id_module', 3)->get();
$module->update(['id_module' => 1]);
like this
$foo_2 = Foo::where('id_modul', 2)->get();
$foo_3 = Foo::where('id_modul', 3)->get();
foreach ($foo_2 as $foo) {
$foo->id_modul = 3;
$foo->save();
}
foreach ($foo_3 as $foo) {
$foo->id_modul = 2;
$foo->save();
}

Laravel Function at Scheduler

I have a laravel 5.2 project and i want to run laravel scheduler by specified time from database data, so i create schedule kernel like this :
protected function schedule( Schedule $schedule )
{
// Run proposal schedule to generate albums
$proposals = Proposal::whereStatus( true )->whereGenerated( false )->get();
foreach ( $proposals as $key => $proposal ) {
$time = date( 'i G ', strtotime( $proposal->duedate ) );
$send_date = date( $time . 'j n * Y', strtotime( $proposal->created_at . ' + ' . $proposal->timeout . ' days' ) );
$schedule->call( function() use( $proposal ) {
$proposal->generateAlbums();
} )->cron( $send_date );
}
}
And it's work fine, until i reset my migration and try to migrate from the begining, i got an error like this
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "proposals" does not exist
So i think it's not good if i place my code there, right??
where should i place my code for this??
Or it's already right and what i need just to check if database table are exists or not??
I need best solution to code just the way laravel provide..
You can check if table exists or not by
if (Schema::hasTable('proposals')) {
//Your code which needs to execute
}

Query error in code igniter ( wrong escape )

I try to insert a row in the table on code igniter from a Array, but something is going wrong.
That's the array:
Array
(
[Date] => 2001-08-15
[Number] => 962883
[Time] => 17:40
[Etc1] => 0
[Etc2] => 0
)
And this the insert:
$this->db->insert('mytable', $myarray);
A new line is inserted, but all columns are empty!
Trying to find de error, I printed the last query by
echo $this->db->last_query() ." <br>";
And I got:
INSERT INTO `mytable` (`Date`, `Number`, `Time`, `Etc1`, `Etc2`)
VALUES
('\02\00\00\01\0-\00\08\0-\01\05\0', '\09\06\02\08\08\03\0', '\01\07\0:\04\00\0', '\00\0', '\00\0')
For some reason I can not get, the codeigniter ( or PHP ) is wrongly escaping the values.
Any Idea?
Firstly your change your array like this:
$data_array = Array
(
'Date'=> 2001-08-15
'Number' => 962883
'Time' => 17:40
'Etc1' => 0
'Etc2' => 0
);
$this->your_model->insert_data($data_array);
and inside your model write function like this
function insert_data($data=array())
{
$this->db->trans_start();
$this->db->insert('your_table_name',$data);
$this->db->trans_complete();
return TRUE;
}
i hope this will solve your problem
try this , this may help.
$this->db->set('Date', '2001-08-15', FALSE);
$this->db->set('Number', '962883', FALSE);
$this->db->set('Time', '17:40', FALSE);
$this->db->set('Etc1', '0', FALSE);
$this->db->set('Etc2', '0', FALSE);
this->db->insert('mytable');
I tried emulating your problem and was able to get the correct SQL statement genrated.
But I am pasting here the code that worked for me:
$data = array
(
'Date' => '2001-08-15',
'Number' => '962883',
'Time' => '17:40',
'Etc1' => '0',
'Etc2' => '0'
);
$this->db->insert('mytable', $data);
Let me know if this works - and if not, what the error message is.

Linq All with a condition

DB:
I'm trying to bring back data only when All of the ReviewItems meet the condition of ReviewItemStatus==3. This works.
Problem: But then I want to narrow the scope of All to all ReviewItems where ReviewerID==1000
// I want ALL groupAccountLinks only for ReviewerID==1000 and AccountID
// 0) (and thus ReviewItems) for Account Charlie have ReviewItemStatusID==3
var xx = Accounts.Where(acc => acc.GroupAccountLinks.All(gal =>
// do ANY of the (1) associated reviewItems contain ri.ReviewItemStatusID == 3
gal.ReviewItems.Any(ri => ri.ReviewItemStatusID == 3)
// This doesn't work
//&& ri.Review.ReviewerID == 1000
)
&& acc.AccountID == 1002 // Charlie
);
Will be going against EF4.1 Currently testing using Linqpad and LinqToSQL test db.
You have && Condition .So, I think your table not have all AccountId=1002 and All ReviewItemStatusID =3 . So Change && condition to || condition.
The first thing I would do would be to take the && acc.AccountID == 1002 off and make sure that you're getting the entire unfiltered set of Accounts that have a ReviewItem in status 3. If that looks good try doing your filter this way:
var xx = Accounts
.Where(acc => acc.GroupAccountLinks
.All(gal => gal.ReviewItems
.Any(ri => ri.ReviewItemStatusID == 3))
.FirstOrDefault(acc => acc.AccountID == 1002);
Thanks to Jesse, Slauma and RemeshRams which lead me to this:
var xxx = Accounts.Where(
// do All Accounts satisfy condition
u => u.Accounts.All(
// do All GroupAccountLinks (and thus ReviewItems) for Account meet the condition of ReviewItemStatusID==3
acc => acc.GroupAccountLinks.All(
// for ReviewItems where ReviewerID==1000, do they All have ReviewItemStatusID==3
gal => gal.ReviewItems.Where(
ri => ri.Review.ReviewerID == 1000)
.All(
ri => ri.ReviewItemStatusID == 3
)
// Make sure there are some ReviewItems
&& gal.ReviewItems.Any()
)
)
);

LINQ and 2 datatables

I have 2 datatables in a dataset. One table has a list called CostTypes. Just an Id and Description field.
The other datatable is the master table and has many records and one of the columns is the cost type. There will be cost types that are not reference in this datatable. There is another column in this databale called cost.
What I am trying to do is get a summary by cost type with a total of the cost. But I want ALL cost types listed any values not in the master table will be zero.
CostType table
Id, Description
1,Marketing
2,Sales
3,Production
4,Service
Master table
Id, Cost, CostTypeId
1,10,1
2,120,1
3,40,3
So I would like to see a result in a datable (if possible) so I can bind to datagridview
Marketing 130
Sales 0
Production 40
Service 0
Thanks for the help everyone, this is what I came up from the answers - Can anyone suggest any improvements???
Also how can I convert the result in query1 into a datable???
var query1 =
from rowCT in costTypes.AsEnumerable()
from rowSTD in stdRates.AsEnumerable()
.Where( d => d.Field<int?>( "CostTypeId" ) == rowCT.Field<int?>( "CostTypeId" ) )
.DefaultIfEmpty()
group new { row0 = rowCT, row1 = rowSTD }
by rowCT.Field<string>( "Description" ) into g
select new
{
g.Key,
Cost = g.Sum( x => x.row1 == null ? 0 : x.row1.Field<decimal>( "Cost" ) ),
TotalCost = g.Sum( x => x.row1 == null ? 0 : x.row1.Field<decimal>( "TotalCost" ) ),
TotalHours = g.Sum( x => x.row1 == null ? 0 : x.row1.Field<decimal>( "TotalHours" ) ),
TotalLabourCost = g.Sum( x => x.row1 == null ? 0 : x.row1.Field<decimal>( "TotalLabourCost" ) )
}
;
Maybe something like this:
Test data:
DataTable dt=new DataTable();
dt.Columns.Add("Id",typeof(int));
dt.Columns.Add("Description",typeof(string));
dt.Rows.Add(1,"Marketing");
dt.Rows.Add(2,"Sales");
dt.Rows.Add(3,"Production");
dt.Rows.Add(4,"Service");
DataTable dt2=new DataTable();
dt2.Columns.Add("Id",typeof(int));
dt2.Columns.Add("Cost",typeof(int));
dt2.Columns.Add("CostTypeId",typeof(int));
dt2.Rows.Add(1,10,1);
dt2.Rows.Add(2,120,1);
dt2.Rows.Add(3,40,1);
Linq query
var query=(
from row in dt.AsEnumerable()
from row1 in dt2.AsEnumerable()
.Where (d =>d.Field<int>("Id")==row.Field<int>("Id") )
.DefaultIfEmpty()
group new{row,row1}
by row.Field<string>("Description") into g
select new
{
g.Key,
Cost=g.Sum (x =>x.row1==null?0:x.row1.Field<int>("Cost"))
}
);
Result
Key Cost
Marketing 10
Sales 120
Production 40
Service 0
You can use the Sum extension method to compute the cost. It will return 0 if the collection is empty which is exactly what you want:
var costTypes = new DataTable("CostTypes");
costTypes.Columns.Add("Id", typeof(Int32));
costTypes.Columns.Add("Description", typeof(String));
costTypes.Rows.Add(1, "Marketing");
costTypes.Rows.Add(2, "Sales");
costTypes.Rows.Add(3, "Production");
costTypes.Rows.Add(4, "Service");
var costEntries = new DataTable("CostEntries");
costEntries.Columns.Add("Id", typeof(Int32));
costEntries.Columns.Add("Cost", typeof(Int32));
costEntries.Columns.Add("CostTypeId", typeof(Int32));
costEntries.Rows.Add(1, 10, 1);
costEntries.Rows.Add(2, 120, 1);
costEntries.Rows.Add(3, 40, 3);
var costs = costTypes
.Rows
.Cast<DataRow>()
.Select(
dr => new {
Id = dr.Field<Int32>("Id"),
Description = dr.Field<String>("Description")
}
)
.Select(
ct => new {
ct.Description,
TotalCost = costEntries
.Rows
.Cast<DataRow>()
.Where(ce => ce.Field<Int32>("CostTypeId") == ct.Id)
.Sum(ce => ce.Field<Int32>("Cost"))
}
);
The result is:
Description|TotalCost
-----------+---------
Marketing | 130
Sales | 0
Production | 40
Service | 0
You can create a new DataSet quite simply:
var costsDataTable = new DataTable("Costs");
costsDataTable.Columns.Add("Description", typeof(String));
costsDataTable.Columns.Add("TotalCost", typeof(Int32));
foreach (var cost in costs)
costsDataTable.Rows.Add(cost.Description, cost.TotalCost);
If the linear search performed by the Where in the code above is a concern you can improve the performance by creating a lookup table in advance:
var costEntriesLookup = costEntries
.Rows
.Cast<DataRow>()
.Select(
ce => new {
Cost = ce.Field<Int32>("Cost"),
CostTypeId = ce.Field<Int32>("CostTypeId")
}
)
.ToLookup(ce => ce.CostTypeId, ce => ce.Cost);
var costs = costTypes
.Rows
.Cast<DataRow>()
.Select(
dr => new {
Id = dr.Field<Int32>("Id"),
Description = dr.Field<String>("Description")
}
)
.Select(
ct => new {
ct.Description,
TotalCost = costEntriesLookup.Contains(ct.Id)
? costEntriesLookup[ct.Id].Sum()
: 0
}
);
I came up with a simpler bit of linq than others seemed to use. Thanks to Martin Liversage for the code to create the input data.
var costTypes = new DataTable("CostTypes");
costTypes.Columns.Add("Id", typeof(Int32));
costTypes.Columns.Add("Description", typeof(String));
costTypes.Rows.Add(1, "Marketing");
costTypes.Rows.Add(2, "Sales");
costTypes.Rows.Add(3, "Production");
costTypes.Rows.Add(4, "Service");
var costEntries = new DataTable("CostEntries");
costEntries.Columns.Add("Id", typeof(Int32));
costEntries.Columns.Add("Cost", typeof(Int32));
costEntries.Columns.Add("CostTypeId", typeof(Int32));
costEntries.Rows.Add(1, 10, 1);
costEntries.Rows.Add(2, 120, 1);
costEntries.Rows.Add(3, 40, 3);
var cte = costTypes.Rows.Cast<DataRow>();
var cee = costEntries.Rows.Cast<DataRow>();
var output = cte.Select(
ct => new {
Description = ct["Description"],
Sum = cee.Where(ce=>ce["CostTypeId"].Equals(ct["Id"])).Sum(ce=>(int)ce["Cost"])
}
);
This may lose efficiency on larger tables since each cost type will search the cost entry table whereas using grouping I suspect you only need one pass over the table. Personally I'd prefer the (to my mind) simpler looking code. It will depend on your use case though.

Resources