I have 2 linq queries. First query does nothing because of unique index and this is OK. But second also does nothing while it should add records . If I bypass first query second query works. Should I refresh entity ? How ?
foreach (var product in productList)
{
cc2nexo_SubiektProduct newproduct = new cc2nexo_SubiektProduct();
newproduct.Name = product.Name;
newproduct.VAT = product.VAT;
newproduct.Id = product.Id;
foreach (var stawkaVAT in myNexo_ExitoEntities.StawkiVat)
{
if (stawkaVAT.Stawka * 100 == tryconvert_dec(newproduct.VAT))
{
newproduct.VAT_Id = stawkaVAT.Id;
}
}
myNexo_ExitoEntities.cc2nexo_SubiektProduct.Add(newproduct);
SurroundWithTryCatchDB(() =>
{
myNexo_ExitoEntities.SaveChanges();
});
}
var orders = (from myorders in myNexo_ExitoEntities.temp_SubiektOrderList
select myorders).ToList();
foreach (var order in orders)
{
cc2nexo_SubiektOrderList neworder = new cc2nexo_SubiektOrderList();
neworder.Data_utworzenia_sprawy = tryconvert_date(order.Data_utworzenia_sprawy);
neworder.Data_modyfikacji_sprawy = tryconvert_date(order.Data_modyfikacji_sprawy);
neworder.Data_umowy = tryconvert_date(order.Data_umowy);
neworder.Id = order.Id;
myNexo_ExitoEntities.cc2nexo_SubiektOrderList.Add(neworder);
SurroundWithTryCatchDB(() =>
{
myNexo_ExitoEntities.SaveChanges();
});
Debug.WriteLine(neworder.LastName);
}
I am receiving an error
Cannot insert duplicate key row in object 'dbo.cc2nexo_SubiektProduct' with unique index 'K_ID'. The duplicate key value is (1).The statement has been terminated
The reason of problem was SurroundWithTryCatchDB procedure not listed in my question. Because first query caused exception due to unique index all next SaveChanges did not work. I have changed my first query to work with unique values and now everything is OK.
Related
My scenario is i have a grid with search option where user can select the column and can do the search, the grid data is coming from various tables. I have attached a sample screen of grid.
User Screen
So i'm trying to create a dynamic query for search but the problem is i can able to search only in main table (schema.Robot) not in Preload tables. whenever i trying to search data data from Preload tables let say from RobotModel table that time getting below error
pq: missing FROM-clause entry for table "robot_models"
Here is my go code
func (r *RobotsRepository) GetRobotsSummary(listParams viewmodel.ListParams, companyID uint) ([]*schema.Robot, int, error) {
mrobots := []*schema.Robot{}
var count int
var order string
if listParams.SortColumn == "" {
listParams.SortColumn = "id"
listParams.SortOrder = 1
} else {
listParams.SortColumn = util.Underscore(listParams.SortColumn)
}
if listParams.SortOrder == 0 {
order = "ASC"
} else {
order = "DESC"
}
var searchQuery string
if listParams.SearchText != "" {
switch listParams.SearchColumn {
case "Robot":
listParams.SearchColumn = "name"
case "Model":
listParams.SearchColumn = "robot_models.name"
}
searchQuery = listParams.SearchColumn +" LIKE '%"+ listParams.SearchText +"%' and Company_ID = " + fmt.Sprint(companyID)
}else{
searchQuery = "Company_ID = " + fmt.Sprint(companyID)
}
orderBy := fmt.Sprintf("%s %s", listParams.SortColumn, order)
err := r.Conn.
Preload("RobotModel", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Name")
}).
Preload("Task", func(db *gorm.DB) *gorm.DB {
return db.Where("Task_Status in ('In-Progress','Pending')").Select("ID, Task_Status")
}).
Preload("CreatedUser", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Display_Name")
}).
Preload("UpdatedUser", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Display_Name")
}).
Where(searchQuery).
Order(orderBy).
Offset(listParams.PageSize * (listParams.PageNo - 1)).
Limit(listParams.PageSize).
Find(&mrobots).Error
r.Conn.Model(&schema.Robot{}).Where(searchQuery).Count(&count)
return mrobots, count, err
}
In searchQuery variable i'm storing my dynamic query.
My question is how can i search data for preload table columns
Here is the sql query which i'm trying to achieve using gorm
SELECT robots.id,robots.name,robot_models.name as
model_name,count(tasks.task_status) as task_on_hand,
robots.updated_at,users.user_name as updated_by
FROM rfm.robots as robots
left join rfm.tasks as tasks on tasks.robot_id = robots.id and
tasks.task_status in ('In-Progress','Pending')
left join rfm.robot_models as robot_models on robot_models.id =
robots.robot_model_id
left join rfm.users as users on users.id = robots.updated_by
WHERE robot_models.name::varchar like '%RNR%' and robots.deleted_at is null
GROUP BY robots.id,robot_models.name,users.user_name
ORDER BY task_on_hand DESC LIMIT 2 OFFSET 0
and sorry for bad English!
Even though you are preloading, you are still required to explicitly use joins when filtering and ordering on columns on other tables. Preloading is used to eagerly load the data to map into your models, not to join tables.
Chain on something like this:
.Joins("LEFT JOIN rfm.robot_models AS robot_models ON robot_models.id = robots.robot_model_id")
I'm not positive if you can use the AS keyword using this technique, but if not, it should be easy enough to adjust your query accordingly.
How can i dynamically change the selected columns in the generated sql query when using a linq expression?
Its a new session for each time the query is executed.
Even when I set the MapExp as null after first creation an then changing the bool value to false, it still generates the column in the sql query.
The code runs in a wpf application.
System.Linq.Expressions.Expression<Func<Entity, Model>> MapExp = x => new Model
{
Id=xId,
Count= LoadFormulaField ? x.Count: null,
...
};
var result = session.Query<Entity>().Select(MapExp))
Your problem seems to be the ternary-conditional as part of the expression which is causing the "Count" column to always be queried.
One option to avoid this could be:
var query = session.Query<Entity>();
IQueryable<Model> result = null;
if (LoadFormulaField)
{
result = query.Select(x => new Model
{
Id = x.Id,
Count = x.Count,
});
}
else
{
result = query.Select(x => new Model
{
Id = x.Id,
});
}
Which would get a little less ugly if you separate in a couple of methods I think.
I've two tables products, stock I want to select all rows from table products that not inserted on stock and i've 2 conditions
1: column products.s_compnay_id = users.u_company_id
2: cloumn stock.s_company_id =users.u_company_id
that's my model
<?php
Class UserProducts_m extends CI_Model{
function index(){
$session_data = $this->session->userdata('logged_in');
$name = $session_data['username'];
$this->db->select('u_company_id');
$this->db->from('users');
$this->db->where('u_username', $name);
$user_data = $query = $this->db->get();
if ($user_data->num_rows() > 0) {
foreach ($query->result_array() as $row_userdata) {
$usercompanyid[] = $row_userdata;
}
$usercompany=$usercompanyid[0]['u_company_id'];
}
$query="select products.* from products where !FIND_IN_SET(products.p_id,select stock.s_p_id from stock and stock.s_company_id=$usercompany and p_company_id=$usercompany)";
$this->db->query($query);
$result= $this->db->get();
if ($result->num_rows() > 0) {
foreach ($result->result_array() as $row_result) {
$product_data[] = $row_result;
}
}
//return $result=$query->result();
}
}
?>
And that's my controller
<?php
Class UserProducts extends CI_Controller {
function index(){
$this->load->model("UserProducts_m");
$this->load->model("user");
$this->load->view("userproducts_v",array(
'userdata'=>$this->user->userdata(),
'userproducts'=>$this->UserProducts_m->index()
));
}
}
?>
that's my errors
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'select stock.s_p_id from stock and stock.s_company_id=1 and p_company_id=1)' at line 1
select products.* from products where !FIND_IN_SET(products.p_id,select stock.s_p_id from stock and stock.s_company_id=1 and p_company_id=1)
Filename: C:/xampp/htdocs/Elvan/system/database/DB_driver.php
Line Number: 691
I suggest you try putting curly braces around the vars in your query statement. Then it should resolve to array values properly.
$query="select products.* from products where
!find_in_set(products.p_id,select stock.s_p_id from stock and
stock.s_company_id = {$usercompanyid[0]['u_company_id']} and
p_company_id = {$usercompanyid[0]['u_company_id']})";
I see a couple other problems.
The line
$result= $this->db->get();
is not needed because $this->db->query($query); already returned a database result object. Do this
$result = $this->db->query($query);
if ($result->num_rows() > 0)
{ ...
Then you have this useless block of code (Pardon me for being blunt)
foreach ($result->result_array() as $row_result)
{
$product_data[] = $row_result;
}
This is useless because your code just copies array values from one array to another. You'll save a lot of code execution with the following which produces the same thing your foreach loop does.
$product_data = $result->result_array();
result->array() returns an array where each item is an array representing a table row.
You did the same thing earlier adding items to the $usercompanyid array. Do this.
if ($user_data->num_rows() > 0)
{
$usercompanyid = $query->result_array();
}
One last problem. It appears that UserProducts_m::index() does not return anything.
You can use the NOT IN sql query for this.
SELECT *
FROM products
WHERE product_id NOT IN (select field name form stock where clause);
I have two tables employee_personals where all the personal record of the employee is stored and telephone_bills where the telephone bills paid to a particular employee is stored for each month. Now in my employeePersonalsController.php I have a function called api_show_employees() which is similar to below :
function api_show_employees() {
//$this->autoRender = false;
//Configure::write("debug",0);
$office_id = '';
$cond = '';
if(isset($_GET['office_id']) && trim($_GET['office_id']) != '') {
$office_id = $_GET['office_id'];
$cond['EmployeePersonal.office_id'] = $office_id;
}
if(isset($_GET['telephoneBillTo']) && isset($_GET['telephoneBillFrom']) ) {
if($_GET['telephoneBillTo'] != '' && $_GET['telephoneBillFrom'] != '') {
$cond['TelephoneBill.bill_from'] = $_GET['telephoneBillFrom'];
$cond['TelephoneBill.bill_to'] = $_GET['telephoneBillTo'];
}
}
$order = 'EmployeePersonal.name';
// $employee = $this->EmployeePersonal->find('all');
$employee = $this->EmployeePersonal->find('all',array('order' => $order,'conditions'=>$cond));
//return json_encode($employee);
}
This functions basically finds all the employees who paid bills in the given period. But I am getting an error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'TelephoneBill.bill_from' in 'where clause'
Models : EmployeePersonal.php:
var $hasMany = array(
'TelephoneBill' => array(
'className' => 'TelephoneBill',
)
);
TelephoneBill.php
public $name = 'TelephoneBill';
var $hasMany = array('EmployeePersonal');
NB: If I skip the bill_from and bill_to conditions, I am getting the results , with TelephoneBill array !
TLDR: use Joins instead.
Details/Notes:
1) it looks like you're using recursive. Don't do that. Use Containable instead.
2) You can't limit the parent model based on conditions against data from a contained/recursive-included table - instead, use Joins.
2b) Or, you could query from the other direction, and query your TelephoneBill with conditions, then contain the EmployeePersonal.
I am a new at Zendframework 2. I am trying to join two tables and display the result.
The two tables are.
Works and Artist . The tables are joined based on artist_id.
STEP 1> Created 2 class(Works , Artist) in Model
STEP 2> In WorksTable I have the following code
class WorksTable extends AbstractTableGateway
{
protected $table ='works';
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
$this->resultSetPrototype = new HydratingResultSet(
new ArraySerializableHydrator(),
new Works()
);
$this->resultSetPrototype->buffer();
$this->initialize();
}
public function fetchAll()
{
$select = $this->getSql()->select();
$select->join('works','artists.artist_id = artist_id ');
//create paginator object to display records
$paginator = new Paginator(
new DbSelect($select, $this->adapter, $this->resultSetPrototype)
);
return $paginator;
}
}
STEP 3> In controller I defined the following code
public function searchAction()
{
$request = $this->getRequest();
$paginator = $this->getWorksTable()->fetchAll();
// $paginator->setItemCountPerPage(12);
$vm = new ViewModel(array(
'poster' => $paginator,
));
$vm->setVariable('paginator', $paginator);
return $vm;
}
For statement $paginator->setItemCountPerPage(12); get error
Message:
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'works'
Has anyone come across this error? Any ideas on how to resolve this?
you join works table to itself, mysql treat it as two separate tables joined but with same name, hence the error.
Use alias for table you join:
$select = $this->getSql()->select();
$select->join(array('w' => 'works'),'artists.artist_id = artist_id ');
but it looks like it is just typo there and table should be artists
There hasn't used artists table begin the query.and also didn't use works table on join.
use Zend\Paginator\Adapter\DbSelect;
use Zend\Db\Sql\Sql;
public function fetchAll()
{
$sql = new Sql($this->tableGateway->getAdapter());
$select = new Select();
$select->from("artists");
$select->columns(array('*'));
$select->join('works','artists.artist_id = works.artist_id',array('your_wanted_column_names,don't mention again artist_id here because there should be a error'));
$paginator = new Paginator(
new DbSelect($select, $this->adapter, $this->resultSetPrototype)
);
return $paginator;