Is there a better way to join query in laravel eloquent.? - mysql

I have two tables and both have separate models from them. first table is users and other table is users_details table I am writing an eloquent query to join the result but I am getting following error
Integrity constraint violation: 1052 Column 'gender' in where clause is ambiguous (SQL: select count(*) as aggregate from `users_details` right join `users` on `users_details`.`user_id` = `users`.`id` where `gender` LIKE female and `matrimonial` LIKE 1)
my code for the query is following.
public function bride(){
$query = app(UserDetail::class)->newQuery();
$query= $query->where('gender','LIKE','female');
$query= $query->where('matrimonial','LIKE','1');
$query = $query->rightJoin('users','users_details.user_id','=','users.id');
$request = request();
if(request()->exists('sort')){
$sorts = explode(',',request()->sort);
foreach ($sorts as $sort){
list($sortCol, $sortDir) = explode('|',$sort);
$query = $query->orderBy($sortCol,$sortDir);
}
}
else {
$query = $query->orderBy('id','asc');
}
if($request->exists('filter')) {
$query->where(function($q) use($request){
$value = "%{$request->filter}%";
$q->where('name','like',$value)
->orWhere('father_name','like',$value)
->orWhere('city','like',$value)
->orWhere('mother_name','like',$value);
});
}
$per_page = request()->has('per_page')?(int) request()->per_page : null;
$pagination = $query->paginate($per_page);
$pagination->appends([
'sort'=>request()->sort,
'filter'=>request()->filter,
'per_page'=>request()->per_page
]);
return response()->json(
$pagination
)
->header('Access-Control-Allow-Origin','*')
->header('Access-Control-Allow-Methods','GET');
}
What should I do to get the result. Thanks

Because there are same column name in your tables(gender in user_details and users), you need to specify the table name with the column, so that mysql can find the true column for you,
like this:
$query= $query->where('user_details.gender','LIKE','female');

SQL doesn't know which table you are talking about when you are using Joins - unless you specify table names for each column mentioned in your query.
Replace these lines:
$query= $query->where('gender','LIKE','female');
$query= $query->where('matrimonial','LIKE','1');
with these lines:
$query= $query->where('users_details.gender','LIKE','female');
$query= $query->where('users_details.matrimonial','LIKE','1');

Related

codeigniter join 3 tables and get data from 1st table where 1st table is linked with 2nd table and 2nd table is linked with 3rd table

user_table(user_id, user_name)
user_group_table(user_id, group_id)
group_table(group_id, group_name)
I need to retrieve data (user_id, user_name, group_name)
How can I join these tables in CodeIgniter?
$this->db->query('SELECT user_table.user_id, user_table.user_name,
group_table.group_name
FROM
user_table
join user_group_table on user_group_table.user_id=user_table.user_id
join group_table on group_table.group_id=user_group_table.group_id')
->result_array();
return it and print/use the array however you like OR you can use Codeigniter Query Builder Class
$where = array(); //if u want to use any condition
$this->db->select('user_table.user_id, user_table.user_name, group_table.group_name');
$this->db->join('user_group_table', 'user_group_table.user_id = user_table.user_id');
$this->db->join('group_table', 'group_table.group_id = user_group_table.group_id');
$result = $this->db->order_by('user_table.user_id', 'desc')->get_where('property', $where)->result_array();
return $result
$this->db->select('user_table.user_id,user_table.user_name,group_table.group_name');
$this->db->from('user_group_table');
$this->db->join('user_table', 'user_table.user_id = user_group_table.user_id');
$this->db->join('group_table', 'group_table.group_id = user_group_table.group_id');
$query = $this->db->get();
$res = $query->result();
return $res;

Updating Multiple Column on MySQL

I want to update members_roosevelt table ACCOUNT column starting with 3000+ value I also want to update ACCOUNT column on loan_roosevelt table that is related to my member_roosevelt. What's wrong with my query? Thank you!
$query1 = "SELECT ACCOUNT
FROM
`members_roosevelt`";
$result_q1 = $link->query($query1) or die($link->error);
while ($obj = $result_q1->fetch_object()) {
$members[] = $obj->ACCOUNT;
}
$ids = implode(',', $members);
$sql = "UPDATE `members_roosevelt` as `memb`
JOIN `loan_roosevelt` as `loan`
ON `memb`.`ACCOUNT` = `loan`.`ACCOUNT`
SET
(`memb`.`ACCOUNT`,
`loan`.`ACCOUNT`) = CASE ACCOUNT";
foreach ($members as $id => $ordinal) {
$sql .= sprintf("WHEN %d THEN %d ", $ordinal, (3000+$id));
}
$sql .= "END WHERE memb.ACCOUNT IN ($ids)";
$link->query($sql) or die($link->error);
SET (`memb`.`ACCOUNT`, `loan`.`ACCOUNT`) = CASE ACCOUNT...
This is simply not part of SQL syntax. You can't set two columns at a time like this. The left side of an assignment operator must be one column.
A better solution is to use a session variable.
SET #acct = 3000;
UPDATE members_roosevelt as memb
JOIN loan_roosevelt as loan
ON memb.ACCOUNT = loan.ACCOUNT
SET memb.ACCOUNT = (#acct:=#acct+1),
loan.ACCOUNT = (#acct);
This way you don't have to run the SELECT query at all, and you don't have to create a huge UPDATE statement with potentially thousands of WHEN clauses.
Demo: SQLFiddle

SQL - SELECT with WHERE statement return false despite present field in table

I am very confused about this (returning false):
$sql = "SELECT * from tbl_user WHERE group = 'abc'";
$res = mysql_query($sql);
if(mysql_num_rows($res) > 0) {
$response = array('status' => '1');
} else {
$response = array('status' => '0'); // ---> what I get back
die("Query failed");
}
...despite the fact the field group is present in mySQL database. Even more strange is that the following return the value of group:
$SQL = "SELECT * FROM tbl_user";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['group']; // ---> returns 'abc'
When I execute a WHERE clause with every other fields of my table excepting group (for example WHERE name = 'ex1' AND ID=1 AND isAllowed=0 (and so on...), everything is fine. As soon as I insert group = 'abc', I get nothing...
This makes me mad. If anyone could help... (I am running a local server with MAMP).
Thanks a lot!
The issue is that group is a reserved word in SQL.
For MySql you need to escape it with backticks
`group`
So your query would be
$sql = "SELECT * from tbl_user WHERE `group` = 'abc'";

php codeigniter MySQL search query

I want to create a search query on MySQL database that will consist of 5 different strings typed in from user. I want to query 5 different table columns with these strings.
When I for example have input fields like:
first name, last name, address, post number, city.
How should I query the database that I dont always get all the rows.
My query is something like this:
SELECT user_id, username
from users
where
a like %?% AND
b like %?% AND
c like %?% AND
d like %?% AND
e like %?%;
When I exchange the AND for OR I always get all the results which makes sense, and when I use AND I get only the exact matches...
Is there any function or statement that would help me with this?
EDIT
The code I use is:
$sql = "select users.user_id, first_name
from users
inner join user_normal_aos
on users.user_id = user_normal_aos.user_id
inner join normal_areas_of_expertise
on user_normal_aos.normal_areas_of_expertise_id = normal_areas_of_expertise.normal_areas_of_expertise_id
where
users.first_name like ? AND
users.kanzlei like ? AND
normal_areas_of_expertise.normal_aoe like ? AND
users.postcode like ? AND
users.city like ?";
$query = $this->db->query($sql,
array(
'%'.$lawyer_name.'%',
'%'.$kanzlei.'%',
'%'.$area_of_expertise.'%',
'%'.$post_code.'%',
'%'.$city.'%')
);
For example use PHP to adjust your query based on what fields you have entered.
$where = array();
$replacements = array();
/* you can also compare if string is not null or not empty...
this is just example using isset */
if (isset($lawyer_name)) {
$where[] = 'users.first_name like ?';
$replacements[] = '%'.$lawyer_name.'%';
}
/* repeat this if again for all your fields .... */
$sql = "..... where ".implode(' AND ', $where);
$query = $this->db->query($sql,
$replacements
);

Zend_Db: How to get the number of rows from a table?

I want to find out how many rows are in a table. The database that I am using is a MySQL database. I already have a Db_Table class that I am using for calls like fetchAll(). But I don't need any information from the table, just the row count. How can I get a count of all the rows in the table without calling fetchAll()?
$count = $db->fetchOne( 'SELECT COUNT(*) AS count FROM yourTable' );
Counting rows with fetchAll considered harmful.
Here's how to do it the Zend_Db_Select way:
$habits_table = new Habits(); /* #var $habits_table Zend_Db_Table_Abstract */
$select = $habits_table->select();
$select->from($habits_table->info(Habits::NAME), 'count(*) as COUNT');
$result = $habits_table->fetchRow($select);
print_r($result['COUNT']);die;
Proper Zend-Way is to use Zend_Db_Select like this:
$sql = $table->select()->columns(array('name', 'email', 'status'))->where('status = 1')->order('name');
$data = $table->fetchAll($sql);
$sql->reset('columns')->columns(new Zend_Db_Expr('COUNT(*)'));
$count = $table->getAdapter()->fetchOne($sql);
This is how it's done in Zend_Paginator. Other option is to add SQL_CALC_FOUND_ROWS before your column list and then get the number of found rows with this query:
$count = $this->getAdapter()->fetchOne('SELECT FOUND_ROWS()');
You could do a
SELECT COUNT(*)
FROM your_table
$dbo->setFetchMode( Zend_Db::FETCH_OBJ );
$sql = 'SELECT COUNT(*) AS count FROM #table';
$res = $dbo->fetchAll( $sql );
// $res[0]->count contains the number of rows
I'm kind of a minimalist:
public function count()
{
$rows = $db->select()->from($db, 'count(*) as amt')->query()->fetchAll();
return($rows[0]['amt']);
}
Can be used generically on all tables.
Add count capability to your Zend_DB Object To count all table rows
public function count()
{
return (int) $this->_table->getAdapter()->fetchOne(
$this->_table->select()->from($this->_table, 'COUNT(id)')
);
}