get distinct record from 3 tables using join in codeigniter - codeigniter

i have three tables
cases,clients,attendance
in cases
id start_date end_date client_id status
1 2012-12-30 2013-01-30 1 new starts
2 2012-12-31 2013-01-31 2 probation
in clients
id Name dob gender status
1 TOM 1987-01-30 M A
2 JERRY 1985-01-31 F D
in attendance
id client_id date status
1 1 2013-01-30 A
2 1 2013-01-31 P
i need result like this
case_id case_start_date case_end_date client_id Name
att_date atte_status
1 2012-12-30 2013-01-30 1 TOM
2013-01-30,2013-01-31 A,P
is this possible? i'm a self learner and i don't have good idea in join query please any body help me....

try this..
$this->db->select('ca.*,ci.Name,a.date,a.status');
$this->db->from('cases'.' ca');
$this->db->join('clients'.' ci','ca.client_id=ci.id','left');
$this->db->join('attendance'.' a','a.client_id=ci.id','left');
return $this->db->get();
go through the user guide if u want to read more about join and active records...

Here's a very simple example to get you started with any number of join common fun for all
Construcor Code
Construct $joins as array:
$joins = array(
array(
'table' => 'table2',
'condition' => 'table2.id = table1.id',
'jointype' => 'LEFT'
),
);
Example function handling joins as an array:
public function get_joins($table, $columns, $joins)
{
$this->db->select($columns)->from($table);
if (is_array($joins) && count($joins) > 0)
{
foreach($joins as $k => $v)
{
$this->db->join($v['table'], $v['condition'], $v['jointype']);
}
}
return $this->db->get()->result_array();
}

Related

Erro Nova ChartJs SQL Generator when using PostgreSQL

Describe the bug
I'm trying to generate a chart, however when I pass the parameter "filter" to SQL Builder, more specifically the file "TotalRecordsController" assembles the query as if I were using MySQL, instead of mounting it for PostgreSQL.
Laravel: 8.40
PHP: 7.4
PostgreSQL: 12
Nova: 3.30
ChartJS: 0.3.5
Linux Mint
Chrome
My Code:
public function cards(Request $request)
{
$process_statuses= [
["label"=>"INITIAL" ,"color" => "#007BFF"],
['label'=>'CONVERTED' ,'color' => '#28A645'],
['label'=>'ERROR' ,'color' => '#DC3544'],
['label'=>'WAITING_TO_ERICH' ,'color' => '#17A2B8'],
['label'=>'WAITING_TO_CONVERT','color' => '#17A2B8']
];
$series = [];
foreach ($process_statuses as $status){
$new_serie = [
'label' => $status['label'],
'filter'=>[
'key'=>'process_status',
'value'=>$status['label']
],
'barPercentage' => 0.5,
'backgroundColor' => $status['color'],
];
$series = [...$series,$new_serie];
}
return [
(new BarChart())
->title('Today Status')
//->model(\App\Models\GoogleOfflineConversion::class)
->model('\App\Models\FacebookOfflineConversion')
->series($series)
->options([
'btnRefresh'=>true,
'uom' => 'hour',
])->width('full'),
];
}
Error:
SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "'INITIAL'"
LINE 1: ... process_status = 'INITIAL' then 1 else 0 end) as 'INITIAL',...
^ (SQL: select HOUR(facebook_offline_conversions.created_at) AS cat, HOUR(facebook_offline_conversions.created_at) AS catorder, sum(1) counted, SUM(CASE WHEN process_status = 'INITIAL' then 1 else 0 end) as 'INITIAL', SUM(CASE WHEN process_status = 'CONVERTED' then 1 else 0 end) as 'CONVERTED', SUM(CASE WHEN process_status = 'ERROR' then 1 else 0 end) as 'ERROR', SUM(CASE WHEN process_status = 'WAITING_TO_ERICH' then 1 else 0 end) as 'WAITING_TO_ERICH', SUM(CASE WHEN process_status = 'WAITING_TO_CONVERT' then 1 else 0 end) as 'WAITING_TO_CONVERT' from "facebook_offline_conversions" where facebook_offline_conversions.created_at >= 2021-10-28 00:00:00 group by "catorder", "cat" order by "catorder" asc)
Migration of the my database:
Schema::create('facebook_offline_conversions', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('company_id')->nullable();
$table->integer('refer_site_id')->nullable();
$table->foreignUuid('site_id')->nullable();
$table->foreignUuid('facebook_ads_site_credential_id')->nullable();
$table->string('crm_order_id')->nullable();
$table->string('fbc')->nullable();
$table->longText('document_number')->nullable();
$table->longText('email')->nullable();
$table->longText('phone_number')->nullable();
$table->float('value')->nullable();
$table->string('currency')->nullable();
$table->longText('city')->nullable();
$table->longText('state')->nullable();
$table->longText('zip_code')->nullable();
$table->longText('country')->nullable();
$table->timestamp('conversion_time')->nullable();
$table->longText('ip_address')->nullable();
$table->longText('browser')->nullable();
$table->string('process_status')->nullable();
$table->integer('tries')->nullable();
$table->boolean('approximated')->default(false);
$table->json('conversion_response')->nullable();
$table->timestamps();
});
I'm resolving this problem. The solution is to change the file "src/api/TotalRecordsController" inside the folder "~/vendor/coroowicaksono/chart-js-integration" so that it suits PostgreSQL.

Laravel how to update multiple id values

Laravel how to update multiple id valus in table
print_r($test); exit();
Array ( [0] => 185 [1] => 216 )
$report = Test::find($test);
$report->status = "A";
$report->save();
Test::whereIn('id', $test)->update(['status' => "A"]);
Good luck

phpfox : how to get my group name?

How can I get the group name I do belong ?
I could get these infos:
$user = Phpfox::getService('user')->get($username, false);
[user_group_id] => 6 [title] =>
user_group_title_3749ea904585437bb7e01c7e1571e162
You can use this query:
SELECT ug.title FROM phpfox_user as u
join phpfox_user_group as ug on ug.user_group_id = u.user_group_id
WHERE u.user_id=1
Then put the result in _p function
Example:
$sUserTitle = Phpfox::getLib('database')->select('ug.title')
->from(':user', 'u')
->join(':user_group', 'ug', 'ug.user_group_id = u.user_group_id')
->where('u.user_id=' . Phpfox::getUserId())
->execute('getSlaveField');
echo _p($sUserTitle)

LINQ - Previous Record

All:
Lets say I have the following table:
RevisionID, Project_ID, Count, Changed_Date
1 2 4 01/01/2016: 01:02:01
2 2 7 01/01/2016: 01:03:01
3 2 8 01/01/2016: 01:04:01
4 2 3 01/01/2016: 01:05:01
5 2 15 01/01/2016: 01:06:01
I am ordering the records based on Updated_Date. A user comes into my site and edits record (RevisionID = 3). For various reasons, using LINQ (with entity framework), I need to get the previous record in the table, which would be RevisionID = 2 so I can perform calculations on "Count". If user went to edit record (RevisionID = 4), I would need to select RevisionID = 3.
I currently have the following:
var x = _db.RevisionHistory
.Where(t => t.Project_ID == input.Project_ID)
.OrderBy(t => t.Changed_Date);
This works in finding the records based on the Project_ID, but how then do I select the record before?
I am trying to do the following, but in one LINQ statement, if possible.
var itemList = from t in _db.RevisionHistory
where t.Project_ID == input.Project_ID
orderby t.Changed_Date
select t;
int h = 0;
foreach (var entry in itemList)
{
if (entry.Revision_ID == input.Revision_ID)
{
break;
}
h = entry.Revision_ID;
}
var previousEntry = _db.RevisionHistory.Find(h);
Here is the correct single query equivalent of your code:
var previousEntry = (
from r1 in db.RevisionHistory
where r1.Project_ID == input.Project_ID && r1.Revision_ID == input.Revision_ID
from r2 in db.RevisionHistory
where r2.Project_ID == r1.Project_ID && r2.Changed_Date < r1.Changed_Date
orderby r2.Changed_Date descending
select r2
).FirstOrDefault();
which generates the following SQL query:
SELECT TOP (1)
[Project1].[Revision_ID] AS [Revision_ID],
[Project1].[Project_ID] AS [Project_ID],
[Project1].[Count] AS [Count],
[Project1].[Changed_Date] AS [Changed_Date]
FROM ( SELECT
[Extent2].[Revision_ID] AS [Revision_ID],
[Extent2].[Project_ID] AS [Project_ID],
[Extent2].[Count] AS [Count],
[Extent2].[Changed_Date] AS [Changed_Date]
FROM [dbo].[RevisionHistories] AS [Extent1]
INNER JOIN [dbo].[RevisionHistories] AS [Extent2] ON [Extent2].[Project_ID] = [Extent1].[Project_ID]
WHERE ([Extent1].[Project_ID] = #p__linq__0) AND ([Extent1].[Revision_ID] = #p__linq__1) AND ([Extent2].[Changed_Date] < [Extent1].[Changed_Date])
) AS [Project1]
ORDER BY [Project1].[Changed_Date] DESC
hope I understood what you want.
Try:
var x = _db.RevisionHistory
.FirstOrDefault(t => t.Project_ID == input.Project_ID && t.Revision_ID == input.Revision_ID -1)
Or, based on what you wrote, but edited:
_db.RevisionHistory
.Where(t => t.Project_ID == input.Project_ID)
.OrderBy(t => t.Changed_Date)
.TakeWhile(t => t.Revision_ID != input.Revision_ID)
.Last()

how to sum column value using group by collection in magento(USING MAGENTO STANDARD)

my table is like this and my collection is
$testmodel=Mage::getModel(test/p1)->getCollection();
my database table is below.
id cat_id rate p_id
1 1 4 1
2 1 2 1
3 1 3 2
4 2 5 3
5 2 3 1
and i want output like this in magento using collection
cat_id rate count_category
1 9 3
2 8 2
i found my PROBLEM correct code is below
$testmodel = Mage::getModel('test/p1')
->getCollection()
->addFieldToSelect('rate')
->addFieldToSelect('cat_id');
$testmodel ->getSelect()
->columns('SUM(rate) as total,COUNT(*) AS countCategory')
->group('cat_id');
if you use mysql4 as this model resource class then go to
Model/Mysql4/P1/Collection.php
here you need to add function
public function addGroupByCatId(){
$subSelect = clone $this->getSelect();
$CountsubSelect = clone $this->getSelect();
$subSelect->reset()
->from(array('rev' => 'youtable', 'SUM( rev.rate)')
->where('main_table.cat_id = rev.cat_id');
$CountsubSelect->reset()
->from(array('countrev' => 'youtable'),'COUNT(countrev.cat_id)')
->where('main_table.cat_id = countrev.cat_id');
$this->getSelect()
->join(
array('r' => 'youtable'),
'main_table.id = r.id',
array(
'review_sum' => new Zend_Db_Expr(sprintf('(%s)', $subSelect)),
'count_category' => new Zend_Db_Expr(sprintf('(%s)', $CountsubSelect)),
))
->group('main_table.cat_id');
return $this;
}
OR: Resouce as resource model then goto
if you use mysql4 as this model resource class then go to
Model/Resource/P1/Collection.php
here you need to add function
public function addGroupByCatId(){
$subSelect = clone $this->getSelect();
$CountsubSelect = clone $this->getSelect();
$subSelect->reset()
->from(array('rev' => 'youtable', 'SUM( rev.rate)')
->where('main_table.cat_id = rev.cat_id');
$CountsubSelect->reset()
->from(array('countrev' => 'youtable'),'COUNT(countrev.cat_id)')
->where('main_table.cat_id = countrev.cat_id');
$this->getSelect()
->join(
array('r' => 'youtable'),
'main_table.id = r.id',
array(
'review_sum' => new Zend_Db_Expr(sprintf('(%s)', $subSelect)),
'count_category' => new Zend_Db_Expr(sprintf('(%s)', $CountsubSelect)),
))
->group('main_table.cat_id');
return $this;
}
and final you get
$testmodel=Mage::getModel(test/p1)->getCollection();
$testmodel->addGroupByCatId();

Resources