I just cant figure out how to get the day, the months and the year from the dates.
Here it is the eloquent
public function query(Detail $model)
{
return $model->newQuery()->leftjoin('fishers','fishers.id', '=','details.fisher_id')
->leftjoin('species','species.id', '=', 'details.species_id')
->leftjoin('purposes','purposes.id', '=', 'details.purpose_id')
->leftjoin('islands','islands.id', '=', 'fishers.island_id')
->leftjoin('preservations','preservations.id', '=', 'details.preservation_id')
->select('fishers.*','details.*','details.indate','islands.island_name','fishers.fisher_first_name','fishers.fisher_last_name','details.weight','species.species_name','purposes.purpose_name','preservations.preservation_name');
}
I have tried to use Month(details.indate) as Month, Year(details.indate) as Year but seems not working. I used date as the datatype for indate and when I do Month(details.indate) as Month I get this error:
SQLSTATE[42S22]: COLUMN NOT FOUND: 1054 UNKNOWN COLUMN 'Month(details.indate)' IN 'field list' (SQL: SELECT fishers.* , details.* , MONTH(details.indate) AS MONTH
This is my datatable columns
protected function getColumns()
{
return [
[ 'data' => 'purpose_name', 'name' => 'purposes.purpose_name', 'title' => 'Purpose' ],
[ 'data' => 'fisher_first_name', 'name' => 'fishers.fisher_first_name', 'title' => 'Fisher Name' ],
[ 'data' => 'preservation_name', 'name' => 'preservations.preservation_name', 'title' => 'Preservation Methods' ],
[ 'data' => 'species_name', 'name' => 'species.species_name', 'title' => 'Species Name' ],
[ 'data' => 'island_name', 'name' => 'islands.island_name', 'title' => 'Island Name' ],
[ 'data' => 'weight', 'name' => 'details.weight', 'title' => 'Weight' ],
[ 'data' => 'indate', 'name' => 'details.indate', 'title' => 'Month' ],
[ 'data' => 'indate', 'name' => 'details.indate', 'title' => 'Year' ],
];
}
can someone help me how to do it?
You need to use the DB::raw function to select expressions using Laravel Eloquent.
For example:
return $model->newQuery()->...
->select(DB::raw('Month(details.indate) as Month'), DB::raw('Year(details.indate) as Year'), 'fishers.*','details.*', ...)
Be sure to add use DB; at the top of your file.
Related
I have one table like:
name
startDate
endDate
units
price
and I show them in a gridview for a given year as follows (index.php in views):
$gridColumns = [
'name',
[
'attribute' => 'january',
'format' => 'currency',
'value' => function ($data) {
if(date("m", strtotime($data["startDate"])) == 1) {
return ($data["price"]*$data["units"]);
}
else {
return "";
}
},
'options' => ['style' => 'max-width:20px;'],
'pageSummary' => true,
],
[
'attribute' => 'february',
'format' => 'currency',
'value' => function ($data) {
if(date("m", strtotime($data["startDate"])) == 2) {
return ($data["price"]*$data["units"]);
}
else {
return "";
}
},
'pageSummary' => true,
],
... until month 12
];
In my search model i have defined:
public $january, $february, $march, $april, $may, $june, $july, $august, $september, $october, $november, $december;
placed them as safe in rules and defining attributes in order to get grid header with sortable items
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 0,
],
'sort' => [
'defaultOrder' => [
'name' => SORT_ASC,
],
'attributes' => [
'name',
'units',
'price',
'january',
'february',
'march',
'april',
'may',
'june',
'july',
'august',
'september',
'october',
'november',
'december',
],
],
]);
but when i try to sort by one of the months it gives an error like:
exception 'PDOException' with message 'SQLSTATE[42S22]: Column not
found: 1054 Unknown column 'january' in 'order clause''
How could I sort by these calculated columns that doesnt exist in the database?
Thanks
I remember to have done this before, but now it does not work and I can't get it out.
[
'label' => 'Sex',
'attribute' => 'gan_sex',
'filter' => [
'1' => 'Male',
'2' => 'Female'
]
],
The output is
1
2
2
1
instead of
Male
Female
Female
Male
What is the problem now? I'd swear I used it just the same way but ...
I do it like this
[
'label' => 'Sex',
'attribute' => 'gan_sex',
'filter' => [
'1' => 'Male',
'2' => 'Female'
],
// translate lookup value
'value' => function ($model) {
$gender = [
'1' => 'Male',
'2' => 'Female'
];
return $gender[$model->gan_sex];
}
]
Possible values for gan_sex must be restricted to 1 and 2.
I have 3 Entities:
Appointment
Doctor (extend fe_users)
Specialization
Dependencies:
Each appointment has exactly one doctor
Each doctor has at least one specialization
Each appointment has at least one specialization - but it can't be
one that its doctor doesn't have
My goal: After a doctor is selected you can choose which specialization of the doctor will be used in order to categorize the appointment - but multiselect should also be possible.
Edit: I came up with this sql to make it clearer what I want in my Select-Field:
SELECT s.name
FROM
tx_appointments_domain_model_specialization s,
fe_users fe,
tx_appointments_doctor_specialization_mm ds,
WHERE fe.username = "###REC_FIELD_doctor###"
AND ds.uid_local = fe.uid
AND s.uid = ds.uid_foreign;
So the part of my TCA of Appointment looks like this now:
It's pretty much all generated by the extension builder except the 'foreign_table_where' in doctor which I found out somehow. But I can't wrap my head around how to set the specialization now.
'doctor' => array(
'exclude' => 1,
'label' => 'doctor',
'config' => array(
'type' => 'select',
'foreign_table' => 'fe_users',
'foreign_table_where' => "AND FIND_IN_SET('1', fe_users.usergroup) ORDER BY fe_users.last_name ASC, fe_users.first_name ASC",
'minitems' => 0,
'maxitems' => 1,
),
),
'specialization' => array(
'exclude' => 1,
'label' => 'specialization',
'config' => array(
'type' => 'select',
'foreign_table' => 'tx_appointments_domain_model_specialization',
'MM' => 'tx_appointments_appointment_specialization_mm',
'size' => 10,
'autoSizeMax' => 30,
'maxitems' => 9999,
'multiple' => 0,
'wizards' => array(
'_PADDING' => 1,
'_VERTICAL' => 1,
'edit' => array(
'module' => array(
'name' => 'wizard_edit',
),
'type' => 'popup',
'title' => 'Edit',
'icon' => 'edit2.gif',
'popup_onlyOpenIfSelected' => 1,
'JSopenParams' => 'height=350,width=580,status=0,menubar=0,scrollbars=1',
),
'add' => Array(
'module' => array(
'name' => 'wizard_add',
),
'type' => 'script',
'title' => 'Create new',
'icon' => 'add.gif',
'params' => array(
'table' => 'tx_appointments_domain_model_appointment',
'pid' => '###CURRENT_PID###',
'setValue' => 'prepend'
),
),
),
),
),
I know I could use something like 'foreign_table_where' => ..."###REC_FIELD_doctor###"... but I have no idea how the whole SQL should look like to get only the doctor's specializations showing.
And I'll probably have to add something like this in ext_tables.php which I got from this answer similar to my problem:
$TCA['tx_appointments_domain_model_appointment']['ctrl']['requestUpdate'] .= ',doctor';
Let's say I have a table
Date Item Qty
15/1/2016 Item1 10
16/1/2016 Item1 20
16/2/2016 Item1 30
18/2/2016 Item1 10
And In the report I want to display like this
Month Qty
01-2016 30
02-2016 40
Please tell me how can I do this in Yii2.
I've tried the following in my SearchModel.
$query = Productsalesdetails::find()
->select(['DATE_FORMAT(date, "%m-%Y"),productname,sum(total) as total'])
->groupBy('DATE_FORMAT(date, "%m-%Y")');
For the query use letteral select and alias for date_format too..
$query = Productsalesdetails::find()
->select( 'DATE_FORMAT(date, "%m-%Y") as m_date, productname, sum(total) as total')
->groupBy ('m_date, productname');
Do the fact you have already the format in select you can use the alias in attributes
<?= GridView::widget([
'dataProvider' => $dataProvider,
'summaryOptions' => ['class' =>'dfenx_pagination_summary',],
'pager' => ['options' => ['class'=> 'pagination pull-right']],
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => '',
'label' => 'Month',
'value' => function ($model) {
return $model->m_date;
},
],
[
'attribute' => 'productname',
'label' => 'Item',
],
[
'attribute' => '',
'label' => 'Total',
'value' => function ($model) {
return $model->total;
},
],
....
]);
this should work without adding $var in model for alias ..
otherwise you your model you need
class YourModel extends \yii\db\ActiveRecord
{
public $m_date;
public $total;
.....
I update an entity (so same id) and I get a validation error on a field which has a 'unique' rule.
I verified in the db that there is no an existing identical field and so I don't understand why I have this error as I update the record so obviously the field exists already because it's itself!
Is it a problem to have a 'unique' rule on patchEntity()?
[
'site_name' => '...',
'datas' => object(App\Model\Entity\User) {
'id' => (int) 653,
'owner_id' => (int) 611,
'extraemails' => [
],
'owner' => object(App\Model\Entity\Owner) {
'id' => (int) 611,
'company' => 'This is the Company name',
'created' => object(Cake\I18n\Time) {
'time' => '2015-06-06T18:07:17+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'modified' => object(Cake\I18n\Time) {
'time' => '2015-06-17T02:44:36+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'[new]' => false,
'[accessible]' => [
'email' => true,
'phone' => true,
'phone2' => true,
'fax' => true,
'company' => true,
'tva_number' => true,
'address' => true,
'postcode' => true,
'city' => true,
'country_id' => true,
'users' => true,
'username' => true,
'origin' => true
],
'[dirty]' => [
'email' => true,
'phone' => true,
'postcode' => true,
'city' => true
],
'[original]' => [
'email' => '...',
'phone' => '...',
'postcode' => '...',
'city' => '...'
],
'[virtual]' => [],
'[errors]' => [
'company' => [
'unique' => 'This company name exists already.'
]
],
'[repository]' => 'Owners'
},
....
EDIT patchEntity() call added
$user = $this->Users->patchEntity($site->users[0], [
'email' => $this->siteDatas['userEmail'],
'phone' => $this->siteDatas['ownerPhone'],
'role' => 'owner',
'active' => 1,
'extraemails' => $this->siteDatas['extraemails'],
'owner' => [
'company' => $this->siteDatas['ownerName'],
'email' => $this->siteDatas['ownerEmail'],
'phone' => $this->siteDatas['ownerPhone'],
'address' => $this->siteDatas['ownerAddress'],
'postcode' => $this->siteDatas['ownerPostcode'],
'city' => $this->siteDatas['ownerCity'],
'country_id' => $this->siteDatas['countryId'],
'web' => $this->siteDatas['ownerWeb'],
'origin' => 'sitra',
],
],
[
'validate' => 'import',
'associated' => [
'Extraemails',
'Owners' => [
'validate' => 'import'
]
]
]);
if ($user->errors()) {
// Here is where I get the 'unique' error
}
So again I verified that no other record in the table have the same 'company' name.
and as you can see in the debug() at the begining of my post, I have a owner->id and it's really the one I want to modify.
Here is the validator
public function validationImport(Validator $validator) {
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create')
->notEmpty('company')
->add('company', 'unique', ['rule' => 'validateUnique', 'provider' => 'table', 'message' => __("This company exists already.")])
...
])
;
return $validator;
}