Joomla: two mysql queries model functions with one view - mysql

I am trying to run two model functions from one view. The first query appears to be working fine.
The second query returns a blank array. I noticed when printing the query to the screen that the queries appear to be joining together and are not separate, like this:
JDatabaseQueryMySQL Object ( [db:protected] => JDatabaseMySQL Object ( [name] => mysql [nameQuote:protected] => ` [nullDate:protected] => 0000-00-00 00:00:00 [dbMinimum:protected] => 5.0.4 [_database:JDatabase:private] => Curling_Schedule [connection:protected] => Resource id #19 [count:protected] => 0 [cursor:protected] => Resource id #72 [debug:protected] => [limit:protected] => 0 [log:protected] => Array ( ) [offset:protected] => 0 [sql:protected] => SELECT team_name, division FROM #_autoschedTeams ORDER BY division [tablePrefix:protected] => encex [utf:protected] => 1 [errorNum:protected] => 0 [errorMsg:protected] => [hasQuoted:protected] => [quoted:protected] => Array ( ) ) [type:protected] => select [element:protected] => [select:protected] => JDatabaseQueryElement Object ( [name:protected] => SELECT [elements:protected] => Array ( [0] => sheet, id ) [glue:protected] => , ) [delete:protected] => [update:protected] => [insert:protected] => [from:protected] => JDatabaseQueryElement Object ( [name:protected] => FROM [elements:protected] => Array ( [0] => #__autoschedPlayingSheets ) [glue:protected] => , ) [join:protected] => [set:protected] => [where:protected] => [group:protected] => [having:protected] => [columns:protected] => [values:protected] => [order:protected] => JDatabaseQueryElement Object ( [name:protected] => ORDER BY [elements:protected] => Array ( [0] => sheet ) [glue:protected] => , ) [union:protected] => [autoIncrementField:protected] => )
Model:
public function getTeams()
{
// Create a new query object.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Select some fields
$query->select('team_name, division');
// From the hello table
$query->from('#__autoschedTeams');
$query->order('division');
$db->setQuery((string)$query);
$teams = $db->loadResultArray();
$div = $db->loadResultArray(1);
$divs = array_unique($div);
$result = [];
foreach($divs as $key)
{
$result[$key] = [];
foreach(array_keys($div, $key) as $index)
{
array_push($result[$key], $teams[$index]);
}
}
return $result;
}
public function getSheets()
{
// Create a new query object.
$db = JFactory::getDBO();
print_r($query);
$query = $db->getQuery(true);
// Select some fields
$query->select('sheet, id');
// From the hello table
$query->from('#__autoschedPlayingSheets');
$query->order('sheet');
//print_r($query);
$db->setQuery($query);
$result = $db->loadResultArray();
return $result;
}
}
relevant code from View:
$teams_sched = $this->get('Teams');
$sheets_sched = $this->get('Sheets');

Change the name of the variable and check with it.
If you are not getting the result again, then print the query echo $query; and check with it.
public function getSheets()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('sheet, id');
$query->from('#__autoschedPlayingSheets');
$query->order('sheet');
$db->setQuery($query);
$Sheets = $db->loadResultArray();
print_r($Sheets);
return $Sheets;
}

Related

Is it possible to add data to the related table after batch insert in Lumen/Laravel?

I am stuck with this problem. I have two tables users and user_credentials which are related to each other by Id column of the users table. Since I'm importing data from csv file, I'm using the insert() method to insert data in the users table instead of create() inside loop (which is a little bit faster I guess).
Is there any way to get the user id of the user for user_credentials table so that I'll be able to use insert() in this table as well
// begin DB transaction
DB::beginTransaction();
// loop through the data
foreach ($data as $key => $value) {
// eliminate the first row
if ($key == 0)
continue;
// check for phone number validation
if (!isset($value[2]) || $value[2] != null || $value[2] != '')
$phoneNumberValidation = null;
// phone number validation
$phoneNumberValidation = $this->validateNumber($value[2]);
if ($phoneNumberValidation != false) {
$user = $this->user::Where('personal_number', $phoneNumberValidation)
->first();
if ($user)
continue;
}
// create the user
$users[] = [
'first_name' => $value[0],
'last_name' => $value[1],
'username' => 'oisf' . $userId++,
'email' => $value[9],
'password' => Hash::make($value[3]),
'address' => $value[4],
'personal_number' => $phoneNumberValidation,
'post_address' => $value[5],
'grad' => $value[6],
'forb' => $value[7],
'offk' => (empty(trim($value[8]))) ? 0 : $value[8],
'approval_date' => ($value[10] != '') ? Carbon::parse($value[10])->startOfDay()->format('Y-m-d H:i:s') : Carbon::now()->format('Y-m-d H:i:s'),
'samtycke' => false,
'status' => 'approved',
'role_id' => ($role) ? $role->id : $newRole->id,
'member' => ($value[10] != '') ? $value[10] : Carbon::now()->format('Y-m-d'),
'note' => $value[11],
'payment_status' => isset($value[12]) && !empty($value[12]) ? $value[12] : 'unpaid',
'username_id' => $userId
];
// I need to change this
UserCredential::create([
'user_id' => 'i want user id here',
'some_column_name' => $value['some_key']
]);
// to this
$userCredentials[] = [
'user_id' => 'i want user id here',
'some_column_name' => $value['some_key']
];
}
$this->user::insert($users);
// and then after above insert, I would like to use
UserCredential::insert($userCredentials);
// commit the transaction
DB::commit();
Try use DB::getPdo()->lastInsertId();, it will get the last inserted id, so if you use that before inserting into UserCredential, you should get the last id.

CakePHP 3: How to count and retrieve data for different periods in one query?

I want to count and retrieve data for different periods like today, total, this week, etc by DATETIME created field.
How to count for example this_week?
Here is starting code:
public function findTotalRegistered(Query $query, Array $options)
{
$total = $query->func()->count('id');
$query
->select([
'total' => $total,
//'today' => $today,
//'this_week' => $this_week,
//'this_month' => $this_month,
//'this_year' => $this_year
]);
return $query;
}
You can achieve this by doing sub-query:
public function findTotalRegistered(Query $query, Array $options)
{
$total = $query->func()->count('id');
$query
->select([
'total' => $total,
'today' => $query->where('DATE(created) = CURDATE()')->count(),
'this_week' => $query->where('YEARWEEK(DATE(created), 1) = YEARWEEK(CURDATE(), 1))')->count(),
'this_month' => $query->where('DATE_SUB(NOW(), INTERVAL 1 MONTH)')->count(),
'this_year' => $query->where('YEAR(created) = YEAR(CURDATE())')->count()
])
->group(created);
return $query;
}
Thanks

Cakephp 3 findAuth join table return array

I am attempting to implement a role based authentication system using a custom finder.
public function findAuth(\Cake\ORM\Query $query, array $options)
{
$query
->select(['id', 'username', 'passwordHash', 'locked', 'roles.role'])
->group('username')
->join([
'table' => 'user_roles',
'conditions' => ['user_roles.userid = Users.id']])
->join([
'table' => 'roles',
'conditions' => ['roles.id = user_roles.role']])
->toArray()
;
return $query;
}
The resulting mysql query i need is:
select users.id, username, passwordHash, locked, group_concat(roles.role) role from users INNER JOIN user_roles on user_roles.userid = users.id INNER JOIN roles on roles.id = user_roles.role group by users.id
What I finally ended up going with is this:
public function findAuth(\Cake\ORM\Query $query, array $options)
{
$query
->select(['id', 'username', 'passwordHash', 'locked'])
->join([
'table' => 'user_roles',
'conditions' => ['user_roles.user_id = Users.id']])
->contain(['UserRoles.Roles'])
->join([
'table' => 'roles',
'conditions' => ['roles.id = user_roles.role']])
->group(['Users.username']);
return $query;
}
This gives me a multi-dimensional array of:
user_roles[index[id, user_id, roles[id, role]]]
in my case I have 2 entries for the index (0 and 1) and I can check the role of the user with the in_array function within a foreach loop

Opencart retriving data from 2 tables

I´m trying to join 2 tables in opencart to make an sales report that specifies taxes (by class, there can be many tax%) for every order. I can only get the values from 1 table, but not 2.
How should I do this?
<?php $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order`, `" . DB_PREFIX . "order_total`");
$ordersr = array();
// Check if there are any rows returned from the query
if ($query->num_rows > 0) {
// Loop through the returned rows for processing
foreach ($query->rows as $result) {
$ordersr[] = array(
'order_id' => $result['order_id'],
'invoice_no' => $result['invoice_no'],
'total' => $result['total'],
'order_status_id' => $result['order_status_id'],
'date_added' => $result['date_added'],
'date_modified' => $result['date_modified'],
'firstname' => $result['firstname'],
'lastname' => $result['lastname'],
'payment_country' => $result['payment_country'],
'payment_method' => $result['payment_method'],
'payment_code' => $result['payment_code'],
'shipping_method' => $result['shipping_method'],
'shipping_code' => $result['shipping_code'],
'currency_code' => $result['currency_code'],
'currency_value' => $result['currency_value'],
'order_status_id' => $result['order_status_id'],
'date_payed' => $result['date_payed']
);
}
} ?>

CakePHP drop down- list usernames and company names

Hey have got a page which allows businesses to send invoices to customers (both individuals and other businesses). The Receiver input field allows the user to select which customer to send the invoice to. At the moment the drop down lists businesses, but we want that list to include individuals (User model/table) too. So if the account (Account model/table) doesn't have a company_name then display the user's username.
Below is what I have tried to try and get it working, doesn't give errors, but doesn't show anything on the drop down list. How could I achieve what we want?
Invoice Controller:
$name = "";
if ('Account.company_name' != null) {
$name = 'Account.company_name';
} else {
$name = 'User.username';
}
$accounts2 = $this->User->find('list', array(
'fields' => array('account_id'), 'conditions' => array(
'id' => $this->Auth->user('id'))));
$accounts = $this->User->Relationship->find('list', array(
'fields' => array('receiver_id'),
'conditions' => array('sender_id' => $accounts2)));
$receivername = $this->Account->find('list', array(
'fields' => array($name),
'conditions' => array(
'id' => $accounts)));
View:
echo $this->Form->input('receiver_id', array(
'label' => 'Receiver: ',
'type' => 'select',
'options' => $receivername));
'Account.company_name' != null
is obviously always true, as a string is not null. So
if ('Account.company_name' != null) {
$name = 'Account.company_name';
} else {
$name = 'User.username';
}
always do $name = 'Account.company_name';
you can define a temporary virtual field 'display_name' and code like below
$this->Account->virtualFields['display_name'] = "IF(Account.company_name='' OR Account.company_name IS NULL, (SELECT u.name FROM users u WHERE u.account_id = Account.id),Account.company_name)";
$list = $this->Account->find('list',array(
'fields' => array('Account.id','Account.display_name')
));