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`
Related
I have a table named purchase_details in where during purchase, I am storing many items' purchase record at a time. During purchase also I am updating items table column opening_balance based on purchased items id, Now I am getting trouble when trying to sum 'purchase details' table quantity's value with 'items' table old opening_balance - in the controller, I am trying something like this-
public function store(Request $request)
{
$grandTotal = $request->input('grand_total');
$paidAmount = $request->input('paid_amount');
$purchase = new Purchase;
$purchase->no = $request->input('no');
$purchase->purchase_date = Carbon::parse($request->purchase_date)->format('Y-m-d');
$purchase->notes = $request->input('notes');
$purchase->supplier_id = $request->input('supplier');
$purchase->total_quantity = $request->input('total_quantity');
$purchase->grand_total = $grandTotal;
$purchase->paid_amount = $paidAmount;
$purchase->due_amount = abs($grandTotal - $paidAmount);
$purchase->save();
$itemDetails = [];
$itemIds = $request->input('itemIds');
$itemQuantities = $request->input('itemQuantities');
$itemPrices = $request->input('itemPrices');
$itemTotals = $request->input('itemTotals');
$orderNotes = $request->input('orderNotes');
foreach ($itemTotals as $key => $total) {
$itemDetails[] = [
'item_id' => $itemIds[$key],
'quantity' => $itemQuantities[$key],
'unit_price' => $itemPrices[$key],
'total_price' => $itemTotals[$key],
];
$openingBalance = Item::where('id', $itemIds[$key])->get(['opening_balance']);
DB::table('items')
->where('id', $itemIds[$key])
->update(['opening_balance' => $openingBalance + $itemQuantities[$key]]);
}
$purchase->purchaseDetails()->createMany($itemDetails);
return back();
}
You use collection as int, edit your code:
$openingBalance = Item::select(['opening_balance'])->where('id', $itemIds[$key])->first()->opening_balance;
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();
I am trying to use two left outer joins with Zend Framework 2's SQL classes but for some reason it is not returning one result but the other one is working fine. I've ran the actual SQL in MySQL Workbench and it returns just like I want but it is not doing it with Zend Framework. Here is my code:
Pure SQL:
SELECT groups.group_name, members.username, groups.id FROM groups
LEFT OUTER JOIN group_admins ON groups.id = group_admins.group_id
LEFT OUTER JOIN members ON group_admins.user_id = members.id
WHERE group_admins.user_id = " . parent::getUserId()['id']
This returns the result I wish, (which can be seen here: http://imgur.com/8ydmn4f)
Now, here is the Zend Framework 2 code I have in place:
$select_admins = new Select();
$select_admins->from(array(
'g' => 'groups',
))
->join(array(
'ga' => 'group_admins'
), 'g.id = ga.group_id')
->join(array(
'm' => 'members'
), 'ga.user_id = m.id', array('username'))
->where(array('ga.user_id' => parent::getUserId()['id']));
$query_group_admin = parent::$sql->getAdapter()->query(parent::$sql->buildSqlString($select_admins), Adapter::QUERY_MODE_EXECUTE);
$group_admins = array();
foreach ($query_group_admin as $group_admin) {
$group_admins[] = $group_admin;
}
// get the group members
$select = new Select();
$select->from(array(
'g' => 'group_members'
))
->join(array(
'm' => 'members'
), 'g.member_id = m.id')
->join(array(
'grp' => 'groups'
), 'g.group_id = grp.id')
->where(array(
'g.group_id' => $group_id
));
$query = parent::$sql->getAdapter()->query(parent::$sql->buildSqlString($select), Adapter::QUERY_MODE_EXECUTE);
$member_username = array();
foreach ($query as $member) {
$member_username[] = $member['username'];
}
// get the rest of the group info
$fetch = $this->gateway->select(array(
'id' => $group_id
));
$row = $fetch->current();
if (!$row) {
return false;
}
return array(
'admins' => implode(", ", $group_admins),
'members' => implode(", ", $member_username),
'info' => $row
);
Controller:
public function grouphomeAction()
{
$id = $this->params()->fromRoute('id', 0);
if (0 === $id) {
return $this->redirect()->toRoute('members/groups', array('action' => 'index'));
}
if (!$this->getGroupsService()->getGroupInformation($id)) {
return $this->redirect()->toRoute('members/groups', array('action' => 'index'));
}
return new ViewModel(array('group_info' => $this->getGroupsService()->getGroupInformation($id)));
}
However, this only shows the group name, group creator and group members but leave the group admins field empty.
Here is the print_r result of the array returned:
Array ( [admins] => [members] => jimmysole, fooboy [info] => ArrayObject Object ( [storage:ArrayObject:private] => Array ( [id] => 2 [group_name] => Tim's Group [group_creator] => timlinden [group_created_date] => 2017-01-16 17:39:56 ) ) )
If it helps, here is a screenshot as well of the page - http://imgur.com/xUQMaUu
Any help would be appreciated!
Thanks.
Basically your joins are INNER JOINS...I know....you must hate Zend right now :p . By default they are INNER JOINS so i assume that is what is wrong. SO try to specify the type of join and you should be fine. You can find more examples here: examples
$select12->from('foo')->join('zac', 'm = n', array('bar', 'baz'), Select::JOIN_OUTER);
I am using Yii2.0 and I have following error when I doing filtering with relationship:
Exception (Database Exception) 'yii\db\Exception' with message
'SQLSTATE[42S22]: Column not found: 1054 Unknown column
'userContact.email' in 'where clause' The SQL being executed was:
SELECT tbl_user.* FROM tbl_user LEFT JOIN tbl_user_contact ON
tbl_user.id = tbl_user_contact.user_id WHERE
userContact.email='me#me.com'
And it is obvious that the table name alias is not given. Following is my code that generate the query above:
Class Files
class User extends ActiveRecord{
public function getUserContacts(){
return $this->hasMany(UserContact::className(), ['user_id' => 'id']);
}
}
class UserContact extends ActiveRecord {
public function getUser(){
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
}
Query
User::find()->joinWith('userContacts', false)
->where(['userContact.email' => $email])
->one();
I follow the instruction given here.
Is there a way to have the alias in the query?
Use method "alias('string')".
User::find()->alias('u')->joinWith(['userContacts' => function($query) use ($email){
$query->alias('uc')->where(['uc.email' => $email])
}])
->one();
Look this API doc
In MySQL, your user table is called tbl_user_contact. However, you are referring to it as userContact, which results in the error.
When adding conditions, you should refer to fields using the actual table name. Here's the proper code:
User::find()->joinWith('userContacts', false)
->where([UserContact::tableName().'.email' => $email])
->one();
You could just replace UserContact::tableName().'.email' with tbl_user_contact.email, but using tableName() is better practice.
ActiveQuery extends of Query, you can use methods of query in ActiveQuery:
$query = \app\models\db\AnuncioConsulta::find();
$query->from(\app\models\db\AnuncioConsulta::tableName() . ' as ac' );
$query->join = [
['INNER JOIN', 'anuncio as a' , ' a.id = ac.anuncio_id AND a.status = 1 '],
['INNER JOIN', 'autor as au' , ' au.id = a.autor_id AND au.agente_inmobiliario = 0 '],
['INNER JOIN', 'usuario as u' , ' u.id = au.object_id '],
];
$query->andWhere('ac.news =:status' , [':status' => 1 ]);
$query->andWhere('ac.delete =:status' , [':status' => 0 ]);
$query->andWhere('u.id =:userId' , [':userId' => Yii::$app->user->id ]);
return new \yii\data\ActiveDataProvider([
'query' => $query,
]);
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")'))