Laravel add values to object based on foreign key - arrays

I have a TABLE A called diagnoses . It has a disease_id and a visit_id. I am trying to return the diagnosis from TABLE A along with the disease name and visit details. I keep getting sql syntax errors. Is there a recommended way to push an objects to the array?
My code is
public function diagnosis_diseases(Disease $disease) {
$id = $disease->id;
$items = DB::select(DB::raw('SELECT * FROM diseases WHERE diseases.id = '.$id.' ;'));
foreach($items as $item){
$diagnosis = DB::select(DB::raw(' select * from diagnoses
where disease_id = '. $id.';' ));
$items->push($diagnosis);
}
dd($items);
}

You might need to use an inner join:
public function diagnosis_diseases(Disease $disease) {
$id = $disease->id;
$items = DB::select(DB::raw('SELECT * FROM diseases WHERE diseases.id = '.$id.' ;'));
foreach($items as $item){
$diagnosis = DB::select(DB::raw(' select * from diagnoses
inner join diseases on diagnoses.id = ' .$id' '));
$items->push($diagnosis);
}
dd($items);
}

Related

Getting value from database custom table not working in wordpress

I have created a wordpress table with wp_compare_post with following column id, user_id, post_id, post_type. I have attached the image of the database.
Below is the coading for viewing data from database
function compare_counting(){
global $wpdb;
//get user id
$user_ID = get_current_user_id();
$sql = "SELECT * FROM $wpdb->compare_post WHERE user_id = '$user_ID '";
$results = $wpdb->get_results($sql) or die(mysql_error());
foreach( $results as $result ) {
echo $result->post_id.',';
}
}
But getting following error.
Notice: Undefined property: wpdb::$compare_post in
I think it could be because you need to use $wpdb->prefix
Try this:
$sql = "SELECT * FROM ".$wpdb->prefix."compare_post WHERE user_id = '$user_ID'";

Using OUTER APPLY with Codeigniter active record

Is it possible to use SQL Server's OUTER APPLY with Codeignter's Active Record?
Not possible. For using Cross Apply or Outer Apply, you need to add a specific function in the file system\database\DB_query_builder.php
that being said, you can add this function (modified from join one) to said file:
public function apply($table, $type = '', $escape = NULL){
if ($type !== '')
{
$type = strtoupper(trim($type));
if ( ! in_array($type, array('CROSS', 'OUTER'), TRUE))
{
$type = 'CROSS';
}
}
else{
$type = 'CROSS';
}
// Extract any aliases that might exist. We use this information
// in the protect_identifiers to know whether to add a table prefix
$this->_track_aliases($table);
is_bool($escape) OR $escape = $this->_protect_identifiers;
// Do we want to escape the table name?
if ($escape === TRUE)
{
$table = $this->protect_identifiers($table, TRUE, NULL, FALSE);
}
// Assemble the APPLY statement
$this->qb_join[] = $join = $type.' APPLY '.$table;
if ($this->qb_caching === TRUE)
{
$this->qb_cache_join[] = $join;
$this->qb_cache_exists[] = 'join';
}
return $this;
}
And then, you can using it like
$this->db->apply('(select * from table_a where table_a.id=table_z.fk_id) as tmp_table');
or something more complete like
$this->db->apply('(select * from table_a where table_a.id=table_z.fk_id) as tmp_table','outer',false);
You can do it by
$this->db->join('comments', 'comments.id = blogs.id', 'outer');
Or
$this->db->query("SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;");
Codeigniter Query Builder and OUTER APPLY example
Possible joins with Codeigniter
(associate with this $this->db->join('comments', 'comments.id = blogs.id', 'outer');)
left
right
outer
inner
left outer
right outer

SQL Joining tables; can you repeat columns?

I'm trying to compose a view that we can use to export our inventory.
I have two tables:
Inventory, which contains the columns Description, Year, Make, Model, and Serial.
Pictures, which contains the columns DocumentBody, MimeType, Serial, and Last Modified.
I'd like to make a view that has all columns from Inventory, and also adds columns for x amount of Pictures related to Serial number.
So if there were two pictures with the same serial number, the resultant table would include these fields:
Description, Year, Make, Model, Serial, DocumentBody1, MimeType1, Last Modified1, DocumentBody2, MimeType2, Last Modified2.
For those Inventory items that only have one picture, the second picture columns would all be null.
Is this something I can even do? From what I'm reading about joins, it doesn't seem possible.
As others have said, you should probably evaluate whether you actually need the view you think you need. But if you really want it, you could use PIVOT in MSSQL:
WITH BaseData AS
(
SELECT Serial
,DocumentBody
,MimeType
,LastModified
,ROWNUMBER() OVER(PARTITION BY Serial ORDER BY LastModified) AS RowNum
FROM Pictures) AS t
),
DocumentPivot AS (
SELECT
Serial
,DocumentBody
,'DocumentBody' + RowNum AS ColumnName
FROM BaseData
),
MimePivot AS (
SELECT
Serial
,MimeType
,'MimeType' + RowNum AS ColumnName
FROM BaseData
),
ModifiedPivot AS (
SELECT
Serial
,LastModified
,'LastModified' + RowNum AS ColumnName
FROM BaseData
)
SELECT Description
,Year
,Make
,Model
,Inventory.Serial
,DocumentBody1
,MimeType1
,LastModified1
,DocumentBody2
,MimeType2
,LastModified2
,...
,LastModified10
FROM Inventory
LEFT OUTER JOIN (
SELECT Serial
,DocumentBody1
,DocumentBody2
,...
,DocumentBody10
FROM DocumentPivot
PIVOT (MAX(DocumentBody) FOR ColumnName IN (DocumentBody1, DocumentBody2, ..., DocumentBody10)) AS P1
) AS Documents
ON Documents.Serial=Inventory.Serial
LEFT OUTER JOIN (
SELECT Serial
,MimeType1
,MimeType2
,...
,MimeType10
FROM MimePivot
PIVOT (MAX(MimeType) FOR ColumnName IN (MimeType1, MimeType2, ..., MimeType10)) AS P2
) AS Mimes
ON Mimes.Serial=Inventory.Serial
LEFT OUTER JOIN (
SELECT Serial
,LastModified1
,LastModified2
,...
,LastModified10
FROM ModifiedPivot
PIVOT (MAX(LastModified) FOR ColumnName IN (LastModified1, LastModified2, ..., LastModified10)) AS P3
) AS Modifieds
ON Modifieds.Serial=Inventory.Serial
Select inventory.*, count(pictures.serial) as picture_count From inventory Left Join pictures On inventory.serial = pictures.serial Where [your where statement]
Use Left Join in case there are no pictures at all. This way you still get back a result.
Update
Actually, after reading your question again, it seems you just want to extend your search results with each additional picture in the system. That's not the best way to do this. The best you can do is just get a row returned for each pic that's in the system.
Select inventory.*, pictures.DocumentBody, pictures.MimeType, pictures.Serial, pictures.Last_Modified From inventory Left Join pictures On inventory.serial = pictures.serial Where [your where statement]
Since there is no "Group By" clause, this will give you 1 row for each picture. Then you can just loop through the results.
Also
There are ways to do this by making temp tables, looping through results within a stored procedure, creating new columns (DocumentBody1, DocumentBody2, etc) for each picture result and adding the data to the new fields, then querying the temp table. But that's a lot to go through I would think.
thanks for the help everyone. In the end, I ended up using PHP to accomplish this with the following code:
<?php
date_default_timezone_set('America/Edmonton');
$serverName = "database";
$connectionInfo = array( "Database"=>"CRM_MSCRM");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
echo "Unable to connect.\n\n";
die( print_r( sqlsrv_errors(), true));
}
else
{
echo "Connected. Selecting trucks...\n\n";
}
$tsql = "SELECT * FROM CRM_MSCRM.dbo.Trader_Export_Simple";
$stmt = sqlsrv_query( $conn, $tsql);
if( $stmt === false )
{
echo "Error executing query.\n\n";
die( print_r( sqlsrv_errors(), true));
}
$csvData = array();
while ($row = sqlsrv_fetch_array($stmt))
{
$count = 1;
$mainpicsql = "SELECT * FROM CRM_MSCRM.dbo.TruckImages WHERE Serial = '".$row[0]."' AND MainPic = 1";
$mainpicstmt = sqlsrv_query( $conn, $mainpicsql);
while ($mainpicrow = sqlsrv_fetch_array($mainpicstmt))
{
$truck = $mainpicrow[1];
$mainfilename = $truck ."-". $count . ".png";
file_put_contents($mainfilename, base64_decode($mainpicrow[0]));
$mainpicdate = $mainpicrow[3]->format("d/m/Y h:m:s");
$mainfilename = "http://images.website/images/".$mainfilename;
echo $mainpicdate."\n";
}
$picsql = "SELECT * FROM CRM_MSCRM.dbo.TruckImages WHERE Serial = '".$row[0]."' AND MainPic = 0";
$picstmt = sqlsrv_query( $conn, $picsql);
$extrapicsdate = "";
$filenames = "";
while ($picrow = sqlsrv_fetch_array($picstmt))
{
$count++;
$filename = $picrow[1] ."-". $count . ".png";
file_put_contents($filename, base64_decode($picrow[0]));
$picdate = $picrow[3]->format("d/m/Y h:m:s");
$filenames .= "http://images.website/images/".$filename.";";
$extrapicsdate .= $picdate.";";
}
$filenames = rtrim($filenames, ";");
$extrapicsdate = rtrim($extrapicsdate, ";");
echo $filenames."\n";
echo $extrapicsdate."\n";
if ($truck != "") {
$csvData[] = array($truck, $mainfilename, $mainpicdate, $filenames, $extrapicsdate);
}
if ($filenames != "")
{
$filenames = "";
}
if ($extrapicsdate != "")
{
$extrapicsdate = "";
}
echo "Next truck...\n\n";
$truck = "";
$mainfilename = "";
$mainpicdate = "";
}
$fp = fopen('file.csv', 'w');
foreach ($csvData as $fields) {
fputcsv($fp, $fields);
}
//print_r($csvData);
sqlsrv_free_stmt( $stmt);
sqlsrv_free_stmt( $picstmt);
sqlsrv_close( $conn);
?>
this gets the files out but I still have to merge the resultant CSV with the main "information" CSV.

How to add IN statement with JOIN ON clause in tablegateway ZF2

Getting all result so far until I added a 'IN' statement with join ON clause
My code is something like this:
// $this->table = 'category';
$sql = $this->getSql();
$select = $sql->select();
$select->join('user_category_subscriptions', 'user_category_subscriptions.category_id = category.id AND user_category_subscriptions.status IN (1,2,3,4)', array(), 'left');
$select->where(array('category.user_id = 2 OR (user_category_subscriptions.status IN (2,4))'));
Error
ZEND\DB\ADAPTER\EXCEPTION\INVALIDQUERYEXCEPTION
File:E:\htdocs\myproj\vendor\zendframework\zendframework\library\Zend\Db\Adapter\Driver\Pdo\Statement.php:245
Message:Statement could not be executed
Used 'echo $select->getSqlString();' to print the query:
SELECT "categories".* FROM "categories"
LEFT JOIN "user_category_subscriptions"
ON "user_category_subscriptions"."category_id" = "categories"."category_id" AND "user_category_subscriptions"."status" IN ("1""," "2""," "3""," "4")
WHERE category.user_id = 2 OR (user_category_subscriptions.status IN (2,4))
So the problem is zend's auto converting (1,2,3,4) into ("1""," "2""," "3""," "4")
Any idea to solve this? Thanks
I think you can pass an expression instead of the join string:
// $this->table = 'category';
$sql = $this->getSql();
$select = $sql->select();
$join = new Expression('user_category_subscriptions.category_id = category.id AND user_category_subscriptions.status IN (1,2,3,4)');
$select->join('user_category_subscriptions', $join, array(), 'left');
$select->where(array('category.user_id = 2 OR (user_category_subscriptions.status IN (2,4))'));
try this
$select->where
->AND->NEST->equalTo('category.user_id', 2)
->addPredicate(new Sql\Predicate\In('user_category_subscriptions.status', array(2,4)));

CakePHP 3 find() with beforeFind() callback SQL issue

I'm having a problem with data integrity when using find() in my controller in conjunction with beforeFind() in a behavior callback. The WHERE Submissions.site_id is not being added in the WHERE clause like it should be. I get different result sets depending on where the WHERE clause is set.
in my SubmissionsController:
public function index()
{
$query = $this->Submissions->find('all')
->where(['user_id' => $this->Auth->user('id')])
->contain(['Users', 'Categories']);
$this->set('submissions', $this->paginate($query));
}
In my beforeFind() Model callback (attached as a 'TenantBehavior' to
$query->where([$this->_table->alias().'.'.'site_id' => 3]);
The problem is that with the above, the SQL generated puts the "WHERE" clause as an AND on the JOIN condition like so, and NOT on the actual WHERE:
...
FROM
submissions Submissions
INNER JOIN users Users ON (
Users.id = (Submissions.user_id)
AND Users.site_id = 3
)
INNER JOIN categories Categories ON (
Categories.id = (Submissions.category_id)
AND Categories.site_id = 3
)
WHERE
user_id = 315
If I remove the beforeFind() ->where and instead place it on the controller ->where I get the expected SQL and result set like so:
...
FROM
submissions Submissions
INNER JOIN users Users ON (
Users.id = (Submissions.user_id)
AND Users.site_id = 3
)
INNER JOIN categories Categories ON (
Categories.id = (Submissions.category_id)
AND Categories.site_id = 3
)
WHERE
(
user_id = 315
AND Submissions.site_id = 3
)
Thoughts? Suggestions?
EDIT
As #ndm's suggestion, I began to update and provide much more context. In doing so I discovered (like an idiot) that I was missing the $this->addBehavior('Tenant'); on my 'SubmissionsTable' model. Adding this of course solved the issue.
$query = $this->Submissions->find('all', [
'conditions' => [
'user_id' => $this->Auth->user('id')
],
'contain' => [
'Users',
'Categories',
]
]);
Passing conditions as inline array will solve your issue and append beforeFind() where conditions properly.

Resources