ZendFramework 2:Syntax error or access violation: 1066 Not unique table/alias: - zend-db

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;

Related

second entity query is executed with errors

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.

How to select data from table that not inserted on other table in codeigniter

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);

Eloquent table relations

I am trying to pull a list of characters that belong to a certain user. When I make the request I get an SQL Error. Reading through the error it is trying to us fields that don't exist.
Error:
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'characters' (SQL: select `characters`.*, `characters`.`id` as `pivot_id`,
`characters`.`character_id` as `pivot_character_id`
from `characters` inner join `characters` on `characters`.`id` = `characters`.`character_id` where `characters`.`id` = 1)
"character_id" does not exist in my database. The problem is I can't find where Eloquent is making that field. I looked through the source code and there was a lot of "If this is not provided use $variable.'_id'. I could not find that code anywhere for this though.
Models are below.
class Character extends Eloquent {
protected $guarded = array('id');
protected $table = 'characters';
public function User ()
{
return $this->belongsTo('User', 'id');
}
}
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'users';
protected $hidden = ['password', 'remember_token'];
protected $guarded = ['password'];
public function Character ()
{
return $this->belongsToMany('Character', 'characters', 'id');
}
}
There is a foreign key between user_id in the characters table, and id in the users table.
belongsToMany is for many-to-many relations. Laravel throws you an error because it expects third table - pivot table - containing both character_id and user_id.
If you dont want many-to-many but one-to-many then you should use hasMany and belongsTo.

Yii left join query

I want to execute the below sql query using Yii framework and need help on this.
SQL query
SELECT t.*, LP.name AS lp_name FROM `user` AS `t` LEFT JOIN `level_profiles` AS `LP` ON t.prof_i = LP.id WHERE t.bld_i IN (17)
So, i tried the below steps.
$usql = 't.bld_i IN (17)';
$criteria1 = new CDbCriteria;
$criteria1->select = 't.*, LP.*';
$criteria1->join = ' LEFT JOIN `level_profiles` AS `LP` ON t.prof_i = LP.id';
$criteria1->addCondition($usql);
$criteria1->order = 't.prof_i';
$result = User::model()->findAll($criteria1);
The above step is not allowing me to access the value from 'level_profiles' table.
Then, i tried to execute:
$usql = 't.bld_i IN (17)';
$result = User::model()->with('level_profiles', array(
'level_profiles'=>array(
'select'=>'name',
'joinType'=>'LEFT JOIN',
'condition'=>'level_profiles.id="prof_i"',
),
))->findAll($usql);
This is returning an error 'Relation "level_profiles" is not defined in active record class "User". '
I know this could be executed using the below method.
Yii::app()->db->createCommand('SELECT query')->queryAll();
But i dont want to use the above.
I am a beginner with Yii and tried to look into the forums. But, i am getting confused how to execute the query using "User::model()" approach .
class User extends CActiveRecord
{
......
public function relations()
{
return array(
'level_porfile_relation'=>array(self::BELONGS_TO, 'Level_Profiles_Modelname', 'prof_i'),
);
}
and your query will be:
$result = User::model()->with('level_porfile_relation')->findAll($usql);

How to get the result of the join operations?

Whenever I tried to execute this sql query in a function module in drupal I am not able to get the results but when I try to execute this in MySQL I can view the result. My code looks like this :
function _get_subject_sub_category() {
$options = array();
$sql = "SELECT father.Subject_Code, child.Subject_Category
FROM {subjects} as child
INNER JOIN {subjects} as father ON (child.Parent_Category = father.Subject_Code
AND child.Level =2 )";
$result = db_query($sql);
foreach ($result as $row) {
$options[$row->father.Subject_Code] = $row->child.Subject_Category;
}
return $options;
}
The error I encountered is in the line $options[$row->father.Subject_Code] = $row->child.Subject_Category;`.
Any help will be highly appreciated.
Try changing this line:
$options[$row->father.Subject_Code] = $row->child.Subject_Category;
To this:
$options[$row->Subject_Code] = $row->Subject_Category;
The name of the table is not in the result. If you need to avoid confusion, you can use alias in your SQL query.
I don't know drupal and don't use php, but I would say :
remove
father. in $row->father.Subject_Code
and
child. in $row->child.Subject_Category
as father and child are just db aliases.