I have database
pls help me.
I want get listViewCount of Content of subscriber as below
SELECT
id,
subscriber_id,
content_id,
started_at,
stopped_at,
view_date FROM
(SELECT
*
FROM
content_view_log
WHERE
subscriber_id = 19
ORDER BY view_date DESC) t GROUP BY content_id;
lstViewCount when use sql above
Pls fix my sql with yii2:
public function search($params)
{
$query = ContentViewLog::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'subscriber_id' => $this->subscriber_id,
'type' => $this->type,
'site_id' => $this->site_id,
]);
$query->groupBy("content_id");
$query->orderBy("id desc");
return $dataProvider;
}
Related
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
I want to put follow query :
SELECT GROUP_CONCAT(`user_id` SEPARATOR ',') FROM `damages` WHERE `server_id`=2
in my main query:
$q = new Query();
$dataProvider = new ActiveDataProvider([
'query' => Ticket::find()->where(['user_id' => Yii::$app->user->identity->id])
->andWhere(['in', 'user_id', [$q->select(["GROUP_CONCAT(`user_id` SEPARATOR ',')"])->from('damages')->where(['server_id' => Yii::$app->user->identity->id])]]) ,
]);
it's error:
Object of class yii\db\Query could not be converted to string
and when change main query to :
andWhere(['in', 'user_id', $q->select(["GROUP_CONCAT(user_id SEPARATOR ',')"])->from('damages')->where(['server_id' => Yii::$app->user->identity->id])])
output is nothing.
How to solved this error?
You can fire direct Query
$projceCities = Client::findBySql('SELECT GROUP_CONCAT(DISTINCT(c_state_id)) as c_state_id FROM `ls_client`')
->asArray()
->one();
Result will be like
Array
(
[c_state_id] => 6,10,3,22,2
)
for andWhere you can use literal where
$q = new Query();
$dataProvider = new ActiveDataProvider([
'query' => Ticket::find()->where(['user_id' => Yii::$app->user->identity->id])
->andWhere(" user_id in (SELECT GROUP_CONCAT(`user_id` SEPARATOR ',') FROM damages where server_id = " .
Yii::$app->user->identity->id . ");") ,
]);
but looking at your code could be you need
$q = new Query();
$dataProvider = new ActiveDataProvider([
'query' => Ticket::find()->where(['user_id' => Yii::$app->user->identity->id])
->andWhere(" user_id in (SELECT `user_id` FROM damages where server_id = " . Yii::$app->user->identity->id . ");") ,
]);
In my CakePHP 2.7.7 app, I have an issue where using PaginatorComponent isn't properly sorting my results. See this link for an image:
Sample Data
The data should be sorted by descending last name, but you can see there are a couple users who are seemingly exempt from this data. Doesn't matter what order I do it in, ascending or descending, these few records don't get sorted. For reference:
index() in UsersController:
public function index() {
$this->User->contain('Status');
$this->paginate = array(
'limit' => 15,
'order' => array('User.last_name' => 'DESC'),
'conditions' => array('User.department_id =' => $this->Session->read('Auth.User.department_id')),
'contain' => 'Status'
);
$this->set('users', $this->Paginator->paginate());
}
Any ideas what could have caused this? I'm at a loss here. Thanks in advance!
SELECT `User`.`id`, `User`.`first_name`, `User`.`last_name`, `User`.`middle`, `User`.`address`, `User`.`address_2`, `User`.`city`, `User`.`state_id`, `User`.`zip`, `User`.`home`, `User`.`cell`, `User`.`work`, `User`.`email`, `User`.`status_id`, `User`.`status_reason`, `User`.`rank`, `User`.`birthday`, `User`.`gender`, `User`.`school`, `User`.`employer`, `User`.`position`, `User`.`created`, `User`.`modified`, `User`.`updated_by`, `User`.`radio`, `User`.`ident`, `User`.`parent_name`, `User`.`parent_number`, `User`.`parent_email`, `User`.`squad`, `User`.`squad_leader`, `User`.`ride_along`, `User`.`drivers_license`, `User`.`username`, `User`.`password`, `User`.`department_id`, `User`.`join_date`, `User`.`group_id`, `User`.`test`, (CONCAT(`User`.`first_name`, " ", `User`.`last_name`)) AS `User__name`, `Status`.`id`, `Status`.`status` FROM `admin_cake`.`users` AS `User` LEFT JOIN `admin_cake`.`statuses` AS `Status` ON (`User`.`status_id` = `Status`.`id`) WHERE `User`.`department_id` = 1 ORDER BY `User`.`last_name` ASC LIMIT 15
When you use $this->paginate to set conditions, limit...you need to use function $this->pagination().
$this->pagination and $this->Paginator->pagination() can not be combined.
1)
public function index() {
$this->User->contain('Status');
$this->paginate = array(
'limit' => 15,
'order' => array('User.last_name' => 'DESC'),
'conditions' => array('User.department_id =' => $this->Session->read('Auth.User.department_id')),
'contain' => 'Status'
);
// Assign settings
$this->Paginator->settings = $this->paginate;
$this->set('users', $this->Paginator->paginate());
}
2)
public function index() {
$this->User->contain('Status');
$this->paginate = array(
'limit' => 15,
'order' => array('User.last_name' => 'DESC'),
'conditions' => array('User.department_id =' => $this->Session->read('Auth.User.department_id')),
'contain' => 'Status'
);
//Don't use $this->Paginator->paginate()
$this->set('users', $this->paginate());
}
i am using sqldataprovider and i am geting a Call to a member function getCount() on a non-object error. i dont know what have i done wrong. below is my controller code
public function actionTicketbookingreport()
{
$count = Yii::$app->db->createCommand('
SELECT COUNT(*) FROM screen_ticket_booking_history WHERE status=:status
', [':status' => 0])->queryScalar();
$dataProvider = new SqlDataProvider([
'sql' => 'SELECT A1.booking_id As Booking_id,
A1.booking_date As Booking_date,
A2.movie_name As Movie,
A3.theatre_name As Theatre,
A1.amount As Amount
FROM
screen_ticket_booking_history A1
LEFT OUTER JOIN movies A2 ON A1.movie_id=A2.id
LEFT OUTER JOIN theatres A3 ON A1.theatre_id=A3.id
LEFT OUTER JOIN users_backend A4 ON A3.users_backend_id=A4.id
WHERE A1.booking_date >= :start_date
AND A1.booking_date <= :end_date
AND A3.users_backend_id = :id',
'params' => [':start_date' => $year_start,':end_date'=>$year_end,':id'=> $userid],
'totalCount' => $count,
]);
// get the user records in the current page
$models = $dataProvider->getModels();
//no dataprovider
return $this->render('index',
[ 'model' => $model,
'dataProvider' => $models,
]);
}
Okey I see where what is wrong
return $this->render('index',
[ 'model' => $model,
'dataProvider' => $models,
]);
getModels() returns just an array of elements. If You are trying to generate gridView or something like that You should give whole dataProvider. So it should be
'dataProvider' => $dataProvider,
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;
}