Displaying 61-70 of 268 results.
Wiki: Yii 1.1 new CDbCriteriawiki
posted by admin on November 7, 2016

// создаем экземпляр класса CDbCriteria
$criteria = new CDbCriteria;
// выбираемые все столбцы из всех таблиц, участвующих в запросе
$criteria->select = '*';
//$criteria->select = array('post.id', 'post.category_id', 'post.user_id', 'post.title', 'user.name');
//$criteria->select = 'post.id, post.category_id, post.user_id, post.title, user.name';
// псевдоним(алиас) для текущей таблицы
$criteria->alias = 'post';
// выбираем только неповторяющиеся строки данных
$criteria->distinct = true;
// задаем условие запроса
$criteria->condition = 'post.is_hide = :is_hide AND post.user_id = :author_id';
// группируем
$criteria->group = 'post.category_id';
// условие для GROUP BY
$criteria->having = 'post.viwed > 100';
// задаем соединение с другой(ими) таблицами
$criteria->join = 'LEFT JOIN users as user ON user.id = post.user_id';
// максимальное количество возвращаемых записей
$criteria->limit = 20;
// смещение, с которого будут возвращаться записи
$criteria->offset = 5;
// сортировки результатов запроса
$criteria->order = 'post.date_create';
// параметры для замены в SQL выражении, для condition
$criteria->params = array(':is_hide'=>0, ':author_id'=>Yii::app()->user->id);
// внешние таблицы должны быть связаны с первичной таблицей в одном SQL-запросе
$criteria->together = true;
// получение связанных объектов в режиме "жадной" загрузки
$criteria->with = array('profile', 'comments', 'category');
// добавляем условие between (диапазон)
$criteria->addBetweenCondition('post.date_update', '09-12-2011', '09-12-2015');
// добавляем условие для сравнения переданного списка со значениями столбцов
$criteria->addColumnCondition(array('status'=>1), 'AND')
// добавляем условие IN к уже имеющемуся (condition)
$criteria->addInCondition('post.category_id', array('6', '24', '247'), 'OR');
// добавляем условие к уже имеющемуся (condition)
$criteria->addCondition("count_comments <= :count_comments");
// сливает критерий с другим
if($_POST['search_text']){
$criteriaSearch = new CDbCriteria();
$criteriaSearch->addSearchCondition('description', $_POST['search_text']. true, 'AND', 'LIKE');
$criteria->mergeWith($criteriaSearch, 'AND');
}
$posts = Post::model()->findAll($criteria);
Read more
Wiki: Yii 1.1: CGridView. Add custom class to table rows preserving original odd and evenwiki
posted by admin on November 3, 2016
Lets say we have such a CGridView widget showing a list of users for administrator. Users have status „active“ or „disabled“. Grid widget puts class „odd“ or „even“ to rows and we want to preserve this. So we want to add a class „disabled“ to rows with disabled users.
Implementation

<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'user-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'rowCssClassExpression' => '
( $row%2 ? $this->rowCssClass[1] : $this->rowCssClass[0] ) .
( $data->status ? null : " disabled" )
',
'columns'=>array(
'username',
array(
'name' => 'status',
'value' => '$data->status0->title',
),
array(
'class'=>'CButtonColumn',
'header' => Yii::t( 'app', 'Tools' ),
),
),
));
?>

Comments
$model here is a User model pushed to view from controller. $data->status0->title here is User's property from relation to other model (why it is $data and not $model see bellow).
rowCssClassExpression
All „magic“ we do in „rowCssClassExpression“ property. Its value is a PHP expression. Expression is evaluated for every data row. Result of evaluation is used as the CSS class name. Note, that PHP expression is string.
cssClassExpression
We put „rowCssClassExpression“ property to „top“ CGridView properties – thus class will be aplied to row. If we put another „cssClassExpression“ property to some column – we can set a class for single cell. E.g.:

<?php
array(
'name' => 'status',
'value' => '$data->status0->title',
'cssClassExpression' => '"foo" . (2+3) ."bar"',
),
));
?>

as result we will have

<td class="foo5bar">

(note the difference between „rowCssClassExpression“ and „cssClassExpression“) From widget you can access such a variables:
  • $row : the row number (zero-based)
  • $data : the data model for the row
  • $this : the column object. As you can see we use all of them.

Expressions
This

( $row%2 ? $this->rowCssClass[1] : $this->rowCssClass[0] ) .

evaluates to 0,1,0,1... as rows are processed and original „odd“ or „even“ values are returned. CGridView::rowCssClass property is array containing default class values (in means of html element attribute). This property is ignored in widget because of rowCssClassExpression property is used. But values are accessible :) This expressions then is concatenated (note dot at the end) with:

( $data->status ? null : " disabled" )

$data here is User model and „status“ is its property (0 or 1 in this case). You can't access $model variable from those string expressions.Read more
Not Resolved: MySQL count where columns fields have same value
posted by admin on November 1, 2016
I have rows, and I want count my select with criteria IN and want to count rows, which is having same values for all rows
Example:

id name lastname age
1 Abc defghij 12
2 Def asdasd 15
3 Ghi qwewqeq 18
4 Abc zzzzz 12
5 Abc yyy 12
6 Abc uuuu 12

IN array

1, 4, 5, 6

Same fields:

`name`, `age`

I want to see RESULTS LIKE
Result SELECT:

id name lastname age
1 Abc defghij 12
4 Abc zzzzz 12
5 Abc yyy 12

Result SELECT COUNT(*):

3
Read more
Resolved: Yii 1.1 Change assets folder path directory from assets to another
posted by admin on October 31, 2016
By default we have assets folder, and in server I cant create folder in assets, or copy assets folders with files, I got an internal server error, and website generate js and css errors. How I can change assets folders to another directory.Read more
Resolved: PHP echo link content in page
posted by admin on October 26, 2016
I am working on website and in locale and want to show in my page part of code from live server.
like

echo PHP_LINK_READER_FUNCTION("SOME_URL");
Read more
Resolved: Yii 1.1 listdata multiple fields
posted by admin on October 25, 2016
I have form with select box, and want to generate options with multiple columns.
Now:

$criteria = new CDbCriteria();
...//if you have criteria condition
$type_list=CHtml::listData(Paper::model()->findAll($criteria),'id','title'); ?>
<?php echo $form->dropDownList($model, 'paper_id', array(''=>Yii::t('t', 'Выберите бумагу'))+$type_list, array('options' => array($model->paper_id=>array('selected'=>true)))); ?>

In output i see:
  • Title 1
  • Title 2
  • etc...
  • Title N


But I want multiple columns, and want to see output like this:
  • Title 1, field 1, another field 1, etc...
  • Title 2, field 2, another field 2, etc...
  • ...
  • Title N, field N, another field N, etc...
Read more
Resolved: Laravel Update version to latest version by composer
posted by admin on October 23, 2016
In my project I use Laravel 5.1 and now I want to update by composer to Laravel 5.3 version, it is latest version!
Not manually, by composer or cmd line or artisan command!Read more
Resolved: HTML Hyphen dot string table new row
posted by admin on October 20, 2016
I have table like

<table>
<tr>
<th>id</th>
<th>name</th>
<th>etc...</th>
</tr>
<tr>
<td>C-7788</td>
<td>Arthur</td>
<th>etc...</th>
</tr>
<tr>
<td>C-7w88</td>
<td>John</td>
<th>etc...</th>
</tr>
<tr>
<td>C-7789</td>
<td>King</td>
<th>etc...</th>
</tr>
</table>


In output I got result like:

id | name | etc...
C-
7788 |Arthur | etc
C-
7w88 |John | etc
C-
7789 |King | etc

But I want to see without line breaking result

id | name | etc...
C-7788 |Arthur | etc
C-7w88 |John | etc
C-7789 |King | etc
Read more
Resolved: Laravel 5.2 artisan make Model not created migration file automaticlly
posted by admin on August 11, 2016
I created model from cmd by

php artisan make:model Post


and migration file not created automaticallyRead more
Resolved: Уникальные пары MySQL из одной таблицы. Distinct pairs in MySQL join (same table)
posted by admin on March 21, 2016
Есть таблица товаров.

CREATE TABLE `goods` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(64) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8


Она содержит следующие значения.

`id` `name` 1 Яблоки 2 Яблоки 3 Груши 4 Яблоки 5 Апельсины 6 Груши


Напишите запрос, выбирающий уникальные пары `id` товаров с одинаковыми `name`, например:

(1,2), (4,1), (2,4), (6,3)
Read more