I am trying to fetch data from 2 tables with a join query. Here I have 2 columns in 2 tables with same column name.
This is my query:
public function get_all_expenses()
{
$this->db->select("*",'category.name as cat_name');
$this->db->from('expense');
$this->db->join('category','expense.cat_id = category.id');
$this->db->join('users','expense.user_id = users.id');
$query = $this->db->get();
return $query;
}
I can fetch data of 1 column of 1 table. But I can't fetch data of another column of another table. I am using CodeIgniter.
According to the CodeIgniter documentation the database select method accept a single argument. The correct syntax for the select is then:
$this->db->select('*, category.name as cat_name');
Related
here is a query for fetch data from DB
$subcatgeory = DB::table('subategories')->where('category_id',$item->id)->get();
in a subcategory, there is a column name for subcategory_En values are look like this
subcategory_En
sample data
sample data 2
unassign
i want to skip when the subcategory_En column value is unassign and fetch other data
so I try this query
$subcatgeory = DB::table('subategories')->where('category_id',$item->id)->skip('subcategory_En','unassign')->get();
this query is not working how can I fetch data and skip with column values?
Just do a second where clause.
$subcatgeory = DB::table('subategories')->where('category_id',$item->id)->where('subcategory_En', '!=', 'unassign')->get();
Skip is for limits and offsets.
https://laravel.com/docs/8.x/queries#limit-and-offset
I have two tables 'approval' and 'renewal', both having a common column 'applicant_id'.
When new application comes-in, it stores a data-record in table 'approval' alongwith the 'applicant_id' for whom the record has been added.
Now, when there is a renew applied for that same applicant, the row gets created in the table 'renewal' referencing the 'applicant_id'
Note: There can be a single record in the table 'approval' for a 'applicant_id' but there can be more than one record for the same 'applicant_id' in the table 'renewal'.
Now, my requirement is:
I need to fetch the records from both the table for all the applicants.
Conditions: If there is a data for the 'applicant_id' in both the table and 'renewal' table has multiple row for the same 'applicant_id', then I need to get the records from 'renewal' table only that too the latest one.
If there is no data in 'renewal' table but exists in 'approval' table for the 'applicant_id', then the fetch record should get the data present in 'approval' table.
Basically, if there is record for the applicant in 'renewal' table, get the latest one from there, if there is record present only in 'approval' table, then get that one but the preference should be to get from 'renewal' if exists.
I am trying to do this in laravel 5.2. So, is there anyone who can help me in this?
If you're using Eloquent, you'll have 2 models:
Renewal.php
<?php
namespace App;
use Illuminate\Eloquent\Model;
class Renewal extends Model
{
protected $table = 'renewal';
public static function findMostRecentByApplicantId($applicantId)
{
$applicant = self::where('applicant_id', '=', $applicantId)
->orderBy('date_created', 'desc')
->first();
return $applicant;
}
}
Approval.php
<?php
namespace App;
use Illuminate\Eloquent\Model;
class Approval extends Model
{
protected $table = 'approval';
public static function findByApplicantId($applicantId)
{
$applicant = self::where('applicant_id', '=', $applicantId)
->first();
return $applicant;
}
}
Then, in the code where you want to get the approval/renewal record, use the following code:
if (! $record = Renewal::findMostRecentByApplicantId($applicantId)) {
$record = Approval::findByApplicantId($applicantId);
}
//$record will now either contain a valid record (approval or renewal)
//or will be NULL if no record exists for the specified $applicantId
After few try, I got one way to do it using raw:
SELECT applicant_id, applicant_name, applicant_email, applicant_phone, renewed, updated_at
FROM (
SELECT renewal_informations.applicant_id, renewal_informations.applicant_name, renewal_informations.applicant_email, renewal_informations.applicant_phone, renewal_informations.renewed, renewal_informations.updated_at
FROM renewal_informations
UNION ALL
SELECT approval_informations.applicant_id, approval_informations.applicant_name, approval_informations.applicant_email, approval_informations.applicant_phone, approval_informations.renewed, approval_informations.updated_at
FROM approval_informations
) result
GROUP BY applicant_id
ORDER BY applicant_id ASC, updated_at DESC;
For every single Approval id, there can b multiple records for renewal table suggests you have One to Many relation. which you can define in the your Model like
Approval.php (App\Models\Approval)
public function renewal()
{
return $this->hasMany('App\Models\Renewal', 'applicant_id')
}
Having defined this relation. you can get the records from the table using applicant_id.
$renewal_request_records = Approval::find($applicant_id)->renewal();
This will get all records from renewal table against that applicant_id.
Finding the latest
$latest = Renewal::orderBy('desc', 'renewal_id')->first();
Further Readings Eloquent Relations
is it possible to get the columns names resulting by a query?
So (for example) if I have this query:
SELECT Id AS IdNumber,
(SELECT COUNT(*) FROM tab2 WHERE IdRif = T1.Id) AS TotCount
FROM tab1 T1
I'd like to get:
IdNumber
TotCount
I saw MySQL query to get column names? (and also other questions) but I wasn't able to use it for what I need.
If your query returns results just use the object(fetch_object) / array (fetch_assoc) from the row and use array_keys($row)
if no rows are returned use http://php.net/manual/en/mysqli-result.fetch-field-direct.php
$result = $db->query($sql);
$i = 0;
while ($i < $db->field_count) {
$info = $result->fetch_field_direct($i++);
echo $info->name;
}
as an example
You can fetch the query result into an Associative Array using mysql_fetch_array($result,MYSQL_ASSOC) or $result->fetch_array(MYSQLI_ASSOC) or whatever method you are using, so that the Key=>Value pair of your Associative Array would be your ColumnName=>ColumnValue.
So, irrespective of whether you are using mysql or mysqli, you would be using the same logic to get the column names.
I have a select query in Mysql table to fetch related table with a duplicate values in a specific column(date).This will successfully display columns and its foreign keys if it has duplicate values in a column.Example two rows same value of (2014-11-10) in a date column
mysql>select man_id,date_created,count(date_created) as count
from collections
group by man_id,date_created
having count(date_created) > 1;
I want this query to convert to Doctrine query since I am using symfony 1.4 as a framework
public function getDuplicateDatePayment() {
$q = $this->createQuery()
->select('man_id','date_created','count(date_created) as count')
->from('Collections')
->groupBy('man_id','date_created')
->having('COUNT(c.date_created) > 1');
return $q->execute();
}
SELECT c.id AS c__id, c.man_id AS c__man_id FROM collections c GROUP BY c.man_id HAVING count(c.date_created) > 1 //result 1 row
why does doctrine query does not display results as expected?How to convert said doctrine query so that it will display result similar to SQL?
//result 1141 rows
update
Collections table is related to Man table in a one to many relationship.Do i have to use innerJoin for this?
After two days of trying,searching for an answer, I finally found a solution to my problem.
SELECT c.id AS c__id, c.man_id AS c__man_id FROM collections c GROUP BY c.man_id HAVING count(c.date_created) > 1
The problem of above sql result from doctrine is ,it does not include 'c.loan_id' in groupBy clause,even though I include it in groupBy clause.The solution is ,just add a separated addGroupBy clause ..And now its working.cheers..
public function getDuplicateDatePayment() {
$q = $this->createQuery()
->select('c.man_id','c.date_created','count(c.date_created) as count')
->from('Collections')
->groupBy('c.man_id')
->addGroupBy('c.date_created')
->having('count(c.date_created) > 1');
return $q->execute();
}
I'm working on querying my mysql database via doctrine in a symfony2 app. I have a basic table set up that includes an id number ('id'), name ('name'), and a last column for if the person has been contacted ('contacted'), depicted with 0 or 1. I can query and get the number of total inquiries (depicted in the controller with $inquiryCountTotal just fine.
I'm struggling to count the rows that have been contacted. I figure I can either COUNT the rows with a value of 1 in the contacted column or I could just SUM all the rows in the contacted column.
For some reason it seems to be summing the ids, as I have 8 ids and it's spitting a number of 36.
Where am I going wrong? Thanks in advance!
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('EABundle:Inquiry')
->findBy(array(), array('id'=>'DESC'));
$inquiryCountTotal = $em->createQuery("
SELECT count(id)
FROM EABundle:Inquiry id
")->getSingleScalarResult();
//This is the part I'm struggling with...
$inquiryCount = $em->createQuery("
SELECT sum(contacted)
FROM EABundle:Inquiry contacted
")->getSingleScalarResult();
return $this->render('EABundle:Inquiry:index.html.twig', array(
'entities' => $entities,
'inquiryCount' => $inquiryCount,
'inquiryCountTotal' => $inquiryCountTotal
));
}
Doctrine is interpreting the alias as the id of the entity.
Try this:
$inquiryCount = $em->createQuery("
SELECT sum(i.contacted)
FROM EABundle:Inquiry i
")->getSingleScalarResult();