ZF2 how to rename name of field with join - mysql

Because my join includes a field named 'id' as well, I need to rename this field name during my sql so it won't override my id field name from the first selected tabel.
My query look likes as follow;
$select = new \Zend\Db\Sql\Select();
$select->from('websites');
$select->join(array('s' => 'websites_statistics'), 's.website_id = websites.id');
$select->where(array('websites.website' => $website));
$select->order('s.timestamp DESC')->limit(1);
$rowset = $this->tableGateway->selectWith($select);
$row = $rowset->current();
return $row;
So, 's' 'id' field should be renamed to something like 'stat_id'.
Thanks in advance!
Nick

$select = new \Zend\Db\Sql\Select();
$select->from('websites');
->join(array('s' => 'websites_statistics'), 's.website_id = websites.id',
array('stat_id' => 's.id')); // <-- here is the alias
->where(array('websites.website' => $website));
->order('s.timestamp DESC')
->limit(1);

$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$select->from(array('p' => 'sub_categories'), array('subcategory_id'=>'p.subcategory_id','subname'=>'p.name'))
->join(array('pa' => 'categories'), 'pa.category_id = p.category_id', array('catname'=>'pa.name'));
$result = $this->getAdapter()->fetchAll($select);
*

And also we can use this method
use Zend\Db\Sql\Expression;
->join(array('s' => 'websites_statistics'), 's.website_id = websites.id',
array('stat_id' => new Expression('s.id'))); // <-- here is the alias
This is best method If you have to use Mysql 'AS' on zf2
example : array('Month' => new Expression('DATE_FORMAT(`salesInvoiceIssuedDate`, "%m")'))

Related

Yii2 Left Join in query builder

I have two tables, the report_details and the name. In the report_details table, I have for and from which is an id that is related to the table name. What is the proper syntax in Yii2 to get both the for and from the column on the name table? This is my query so far...
$query = new yii\db\Query;
$query->select('report_details.reference_no, report_details.subject, report_details.doc_for, report_details.doc_from, report_details.doc_date, report_details.doc_name, report_details.drawer_id, report_details.user_id, name.name_id, name.position, name.fname, name.mname, name.lname')
->from('report_details')
->join('LEFT JOIN', 'name', 'report_details.doc_for = name.name_id')
->where(['report_details.reference_no' => $model->reference_no]);
$results = $query->all();
you could use ->leftJoin( )
$query = new yii\db\Query;
$query->select('report_details.reference_no, report_details.subject,
report_details.doc_for, report_details.doc_from,
report_details.doc_date, report_details.doc_name,
report_details.drawer_id, report_details.user_id,
name.name_id, name.position, name.fname, name.mname, name.lname')
->from('report_details')
->leftJoin( 'name', 'report_details.doc_for = name.name_id')
->where(['report_details.reference_no' => $model->reference_no]);
$results = $query->all();

Laravel Get Record ID from Update Query

For this update query, I'm trying to get the id after I run it.
$results = DB::table('testDB123.users')
->where('fbID', '=', $x['id'])
->update([
'updated_at' => $x['currDate'],
'fbFirstName' => $x['firstName'],
'fbLastName' => $x['lastName']
]
);
Tried this with no luck $results->id
Is there anything similar to insertGetId for update queries?
$id = DB::table($table1)->insertGetId([...])
update() method doesn't return an object, so you have two options:
Option 1
Use updateOrCreate():
$user = User::updateOrCreate(['fbID' => $x['id']], $dataArray);
$id = $user->id;
Option 2
Get an object and update it:
$user = User::where('fbID', '=', $x['id'])->first();
$user->update($dataArray);
$id = $user->id;

Last Insert ID is NULL in Laravel

I'm trying to get the last insert ID like so:
$leadData = [
'first_name' => $first_name,
'last_name' => $last_name,
'phone_number' => $phone_number,
'company' => $company,
'email_address' => $email_address,
'iso_code' => $iso_code,
'product' => $product,
'transaction_id' => $transaction_id,
'rep_name' => $rep_name,
'ip_address' => $ip_address
];
//insert lead into DB
$lead = new Lead();
$lead->create($leadData);
//dd($lead);
$leadId = $lead->id;
dd($leadId);
but $leadId is NULL every time. My record is being inserted correctly into the MySQL table. Its a seemingly stupid problem, but has had me stumped for the last hour.
How could $leadID possibly be null?
I figured it out, I had to first assign the return value of ->create() to a variable, and then use the ->id method as in my first example.
changing
$lead = new Lead();
$lead->create($leadData);
$leadId = $lead->id;
to
$lead = new Lead();
$result = $lead->create($leadData);
$leadId = $result->id;
Just keep create object to one variable and print this print this variable object
//insert lead into DB
$lead = new Lead();
$lead->create($leadData);
//dd($lead);
$leadId = $lead->id;
dd($leadId);
to
$lead = new Lead();
$leadData = $lead->create($lead);
//dd($leadData);
$leadId = $leadData->id;
dd($leadId)

WHERE IN with Doctrine 2 DBAL

How to use a WHERE IN clause with Doctrine DBAL ?
The following query doesn't work, it search the name "Bob","Elvis","Bill" (as a string) :
$users = $dbc->fetchAssoc("SELECT * FROM users WHERE name IN(:users_names)", array(
'users_names' => '"Bob","Elvis","Bill"'
));
I tried with an array, it's the same problem.
Try this :
$searchParameters = array("Bob","Elvis","Bill");
$users = "SELECT * FROM users WHERE name IN (?1)";
$q = $em->createQuery($users)
->setParameter(1, $searchParameters);
$result = $q->execute();

Zend Framework 2: LEFT JOIN issue

public function getInterests($userID) {
$result = $this->tableGateway->select(function (Select $select) use ($userID) {
$select->join('interests', 'users_interests.interest_id = interests.interest_id', array('*'), 'left');
$where = new Where();
$where->equalTo('user_id', $userID);
$select->where($where);
});
return $result;
}
Here is my method. It simply selects all records from users_interests with user_id = $userID and joins the 'interests' table. So far, so good, but when trying to display the fetched results, the fields from the joined table just do not exist. Here is the dump of the $result:
Zend\Db\ResultSet\ResultSet Object
(
[allowedReturnTypes:protected] => Array
(
[0] => arrayobject
[1] => array
)
[arrayObjectPrototype:protected] => Object\Model\UsersInterests Object
(
[settings_id] =>
[user_id] =>
[interest_id] =>
)
[returnType:protected] => arrayobject
[buffer:protected] =>
[count:protected] => 2
[dataSource:protected] => Zend\Db\Adapter\Driver\Pdo\Result Object
(
[statementMode:protected] => forward
[resource:protected] => PDOStatement Object
(
[queryString] => SELECT `users_interests`.*, `interests`.* FROM `users_interests` LEFT JOIN `interests` ON `users_interests`.`interest_id` = `interests`.`interest_id` WHERE `user_id` = :where1
)
[options:protected] =>
[currentComplete:protected] =>
[currentData:protected] =>
[position:protected] => -1
[generatedValue:protected] => 0
[rowCount:protected] => 2
)
[fieldCount:protected] => 6
[position:protected] =>
)
I badly need help on this because I am supposed to finish my project until Sunday. Thanks in advance.
You can use the following to apply left join. $select::JOIN_LEFT instead of 'left'.
public function getInterests($userID) {
$result = $this->tableGateway->select(function (Select $select) use ($userID) {
$select->join('interests', 'users_interests.interest_id = interests.interest_id', array('*'), $select::JOIN_LEFT);
$where = new Where();
$where->equalTo('user_id', $userID);
$select->where($where);
});
return $result;
}
It seems you have a problem in the WHERE clause of the join. This also shows in the error here:
[queryString] => SELECT `users_interests`.*, `interests`.* FROM `users_interests` LEFT JOIN .
`interests` ON `users_interests`.`interest_id` = `interests`.`interest_id`
WHERE `user_id` = :where1
Try this:
$select->from($this->table)
->join('interests', 'users_interests.interest_id = interests.interest_id',
array('*'), 'left');
$where = new Where();
$where->equalTo('user_id', $userID) ;
$select->where($where);
I can not follow your code completely, like here:
$this->tableGateway->select(function (Select $select) use ($userID) {
But, here is a very nice article on this. I think, you can simplify your code a little.
Have you iterated over the resultset? You can see there's two matching rows:
[rowCount:protected] => 2
You have a ResultSet object, but it will not load any of the rows until requested, they are "lazy loaded" when you iterate over the object.
You can force the resultset to get them all for you:
var_dump($resultSet->toArray()); // force load all rows
or iterate over the ResultSet:
foreach($resultset as $row) {
var_dump($row); // each row loaded on request
}
I have written about this before and maybe it will help you as well.
TableGateway with multiple FROM tables