Select string using Expression Yii2 is detected as column - yii2

I have a query like this :
use yii\db\Expression;
public function search($params)
{
$query = (new \yii\db\Query())
->select([
"ir.id",
"ir.no_surat",
"tc.level",
"nominal" => 'tc.cleaning',
new Expression("clean as tagihan"),
"tc.ditagihkan_bulan"
])
->from('ydepotras_estimator.repair_estimate as re')
->leftJoin(['ydepotras_estimator.inspection_report as ir'],
"ir.id = re.inspection_id")
->innerJoin(['ydepotras_finance.tagihan_cleaning as tc'],
" re.id = tc.repair_estimate_id");
}
Please see in new Expression("clean as tagihan"),
Yii2 detectedclean as column. But I need the clean as value on tagihan's column
+----+-------------+
| id | tagihan |
+----+-------------+
| 1 | clean |
| 2 | clean |
+----+-------------+
Update
UNION in Yii2
$cleanigQuery = (new \yii\db\Query())
->select([
"ir.id",
"ir.no_surat",
"tc.level",
"nominal" => 'tc.cleaning',
new Expression("clean as tagihan"),
"tc.ditagihkan_bulan"
])
->from('ydepotras_estimator.repair_estimate as re')
->leftJoin(['ydepotras_estimator.inspection_report as ir'],
"ir.id = re.inspection_id")
->innerJoin(['ydepotras_finance.tagihan_cleaning as tc'],
" re.id = tc.repair_estimate_id");
$oneBarQuery = (new \yii\db\Query())
->select([
"ir.id",
"ir.no_surat",
"tob.level",
"nominal" => 'tob.one_bar',
new Expression("one_bar as tagihan"),
"tob.ditagihkan_bulan"
])
->from('ydepotras_estimator.repair_estimate as re')
->leftJoin(['ydepotras_estimator.inspection_report as ir'],
"ir.id = re.inspection_id")
->innerJoin(['ydepotras_finance.tagihan_one_bar as tob'],
" re.id = tob.repair_estimate_id");
So, I can do something like this :
$cleanigQuery->union($oneBarQuery, true);
$query = (new \yii\db\Query())
->select('*')
->from(['u' => $cleanigQuery])
->orderBy('no_surat');
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);

Like this: $query->select("*,CONCAT('clean') as tagihan")

in this case you could use a literal select statement
->select("ir.id, ir.no_surat, tc.level,
tc.cleaning, 'clean' as tagihan, tc.ditagihkan_bulan")

Related

I am failed to retrieve data using DB:table() in laravel

I am failed to retrieve any date with this code
$data = DB::table('students')
->where([
'students.school_id' => $school_id,
'students.status' => true,
'students.class' => $request->class,
'students.section' => $request->section,
'student_attendances.date' => "'$today'",
'students.school_id' => 'student_attendances.school_id'
])
->leftJoin('student_attendances', 'students.rfid_number', '=', 'student_attendances.uid')
->get();
above code returning this query:
select * from `students` left join `student_attendances` on `students`.`rfid_number` = `student_attendances`.`uid` where (`students`.`school_id` = 1 and `students`.`status` = 1 and `students`.`class` = 1 and `students`.`section` = 1 and `student_attendances`.`date` = '2020-03-16' and `students`.`school_id` = student_attendances.school_id)
I have tried this query in mysql database and successfully getting data.
And also below code is working fine :
$sql_query_text = "select * from students left join student_attendances on students.rfid_number = student_attendances.uid where (students.school_id = student_attendances.school_id and students.status = 1 and students.class = '{$request->class}' and students.section = '{$request->section}' and date(student_attendances.created_at) = '$today')";
$data = DB::select($sql_query_text);
I could not understand what is the fault. Please help. Thank you.
the problem is
'students.school_id' => 'student_attendances.school_id'
Joint table condition can not be used in ->where() so I use
->leftJoin('student_attendances', function($join){
$join->on('students.rfid_number', '=', 'student_attendances.uid');
$join->on('students.school_id', '=', 'student_attendances.school_id');
})
And this solved my purpose

Left join in select query Yii2 - Unknown column 'single' in 'on clause'

Why this query is not working?
public function actionInsert()
{
$model = new NotificationsEvents();
$date_at = (new Query())
->select(['single-events.date_at'])
->from('single-events')
->leftJoin('user', 'user.birthday = single-events.date_at');
$event_id = (new Query())
->select(['single-events.id'])
->from('single-events')
->leftJoin('user', 'user.id = single-events.id');
(new Query())->createCommand()->insert('notifications_events', [
'type' => 7,
'date_at' => $date_at,
'event_id' => $event_id,
])->execute();
}
I need to insert user birthday in notifications_events.date_at, and user ID in notifications_events.event_id, but this code is not working:
Unknown column 'single' in 'on clause'
single-events is not a valid/safe name for table, because it contains -. You should either quote it in every possible place:
public function actionInsert() {
$model = new NotificationsEvents();
$date_at = (new Query())
->select(['{{single-events}}.date_at'])
->from('single-events')
->leftJoin('user', 'user.birthday = {{single-events}}.date_at');
$event_id = (new Query())
->select(['{{single-events}}.id'])
->from('single-events')
->leftJoin('user', 'user.id = {{single-events}}.id');
(new Query())->createCommand()->insert('notifications_events', [
'type' => 7,
'date_at' => $date_at,
'event_id' => $event_id,
])->execute();
}
Or use some more practical name for table, like single_events.
Another quoting method: using backtics:
`single-events`

Yii2 where() variable condition

I want when currency = 'sum' sort by and Where(['between', 'price', $min_price, $max_price]) and when currency = 'y.e.' sort by andWhere(['between', 'price', $min_price*2, $max_price*2]). How to write the sql query in yii2?
$anmt_t = (new \yii\db\Query())
->select(['*'])
->from('anmt')
->where(['status' => 'confirmed'])
->andWhere(['between', 'price', $min_price, $max_price, when (currency = 'sum')])
->andWhere(['between', 'price', $min_price*2, $max_price*2, when (currency = 'y.e.')])
->all();
Try using CASE :
$anmt_t = (new \yii\db\Query())
->select(['*'])
->from('anmt')
->where(['status' => 'confirmed'])
->andWhere('
CASE
WHEN currency = "sum" THEN price BETWEEN :mp1 AND :mx1
WHEN currency = "y.e." THEN price BETWEEN :mp2 AND :mx2
END
')
->params([
'mp1' => $min_price,
'mx1' => $max_price,
'mp2' => $min_price * 2,
'mx2' => $max_price * 2,
])
->all();
Not tested
I'd personally favor using Yii2, rather than writing a long query
$condition = currency == 'y.e.' ? ['between', 'price', $min_price *2, $max_price*2] : ['between', 'price', $min_price, $max_price];
then
$anmt_t = (new \yii\db\Query())
->select(['*'])
->from('anmt')
->where(['status' => 'confirmed'])
->andWhere($condition)
->all();

how to set GROUP_CONCAT in query in yii2?

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 . ");") ,
]);

ZF2 how to rename name of field with join

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")'))