Yii2 user profile - yii2

ok so one time i use yii2 with 1 table of user and 1 table of profile(admin,user) and was easy when i connected to the DB, but now i have 3 table of user and when i try to connect it to the DB i have problem...with the function findIdentity
public static function findIdentity($id)
{
$users = Administrador::find()->where(['id_admin'=>$id])->one();
if(!count($users)){
return null;
}
else{
//this->password=$users->passwd;
return new static($users);
}
//return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
as you can see in $users = Administrador::find() i have the name of the table "Administrador" but i want to search the id of the others table too, help please
btw my other 2 table are "contador" and "mecanico" which the id is "id_cont" for contador and "id_mec" for mecanico

Option 1
Add libraries to top of script file:
use someloc/model/Administrator;
use someloc/model/Contador;
use someloc/model/Mecanico
Then:
$users1 = Administrador::find()->where(['id_admin'=>$id])->one();
$users2 = Contador::find()->where(['id_admin'=>$id])->one();
$users3 = Mecanico::find()->where(['id_admin'=>$id])->one();
if (count($users1)) {
return $user1;
} elseif (count($users2)) {
return $user2;
} elseif (count($users3)) {
return $user3;
} else {
....
}
Option 2
Use createCommand in order to use custome SQL statement.
Note: the following query joins results of two tables together.
$sql = "
SELECT
userid
, field2
FROM
(
SELECT
t1.user_id AS userid
, anotherfield AS field2
FROM
table1 t1
UNION
SELECT
t1.user_id AS userid
, anotherfield AS field2
FROM
table2 t2
) x
WHERE
user_id = :user_id
";
$params = [':user_id' => $user_id];
$data = Yii::$app->db->createCommand($sql)->bindValues($params)->queryAll();

Related

PHP/PDO Select from columns multiple conditions

I am trying to obtain results for a given member where status is pending or accepted doing the below:
$status1 = "Pending";
$status2 = "Attended";
$query = $conn->prepare('SELECT * FROM members WHERE member_id=:mID AND status=:status1 OR status=:status2');
$query->execute(array(':mID' => $mID,':status1' => $status1, ':status2' => $status2));
if ($query->rowCount() > 0) {
//start to create my table
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
//create variable, loop through and fill the table etc
}
}else{
echo "something";
}
This displays data - however, it even obtains results not specific to the member id (mID). Meaning other members data too!
I'm clearly missing something and or my query is wrong but struggling to find anything..
Any help appreciated.
You need to look at operator precedence for your database. You're doing this:
SELECT * FROM members WHERE member_id = :mID AND status = :status1 OR status = :status2;
Which most likely results in this:
SELECT * FROM members WHERE (member_id = :mID AND status = :status1) OR status = :status2;
But that's not what you want, so you will have to explicitly use parens like this:
SELECT * FROM members WHERE member_id = :mID AND (status = :status1 OR status = :status2);
Alternatively, you can use IN so that there's no OR:
SELECT * FROM members WHERE member_id = :mID AND status IN (:status1, :status2);

How to convert this query to doctrine DQL

SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid='20'
and not exists (
select 1
from `distribution_mobiletokens`
where userid = '20'
and deviceid = dm.deviceid
and created > dm.created
)
What this query does is selects all mobiletokens where the user id is equal to 20 and the deviceid is the same but chooses the newest apntoken for the device.
My database looks like below.
For more information on this query, I got this answer from another question I asked here(How to group by in SQL by largest date (Order By a Group By))
Things I've Tried
$mobiletokens = $em->createQueryBuilder()
->select('u.id,company.id as companyid,user.id as userid,u.apntoken')
->from('AppBundle:MobileTokens', 'u')
->leftJoin('u.companyId', 'company')
->leftJoin('u.userId', 'user')
->where('u.status = 1 and user.id = :userid')
->setParameter('userid',(int)$jsondata['userid'])
->groupby('u.apntoken')
->getQuery()
->getResult();
//#JA - Get the list of all the apn tokens we need to send the message to.
foreach($mobiletokens as $tokenobject){
$deviceTokens[] = $tokenobject["apntoken"];
echo $tokenobject["apntoken"]."\n";
}
die();
This gives me the incorrect response of
63416A61F2FD47CC7B579CAEACB002CB00FACC3786A8991F329BB41B1208C4BA
9B25BBCC3F3D2232934D86A7BC72967A5546B250281FB750FFE645C8EB105AF6
latestone
Any help here is appreciated!
Other Information
Data with SELECT * FROM
Data after using the SQL I provided up top.
You could use a subselect created with the querybuilder as example:
public function selectNewAppToken($userId)
{
// get an ExpressionBuilder instance, so that you
$expr = $this->_em->getExpressionBuilder();
// create a subquery in order to take all address records for a specified user id
$sub = $this->_em->createQueryBuilder()
->select('a')
->from('AppBundle:MobileTokens', 'a')
->where('a.user = dm.id')
->andWhere('a.deviceid = dm.deviceid')
->andWhere($expr->gte('a.created','dm.created'));
$qb = $this->_em->createQueryBuilder()
->select('dm')
->from('AppBundle:MobileTokens', 'dm')
->where($expr->not($expr->exists($sub->getDQL())))
->andWhere('dm.user = :user_id')
->setParameter('user_id', $userId);
return $qb->getQuery()->getResult();
}
I did this for now as a temporary fix, not sure if this is best answer though.
$em = $this->em;
$connection = $em->getConnection();
$statement = $connection->prepare("
SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid=:userid
and not exists (
select 1
from `distribution_mobiletokens`
where userid = :userid
and deviceid = dm.deviceid
and created > dm.created
)");
$statement->bindValue('userid', $jsondata['userid']);
$statement->execute();
$mobiletokens = $statement->fetchAll();
//#JA - Get the list of all the apn tokens we need to send the message to.
foreach($mobiletokens as $tokenobject){
$deviceTokens[] = $tokenobject["apntoken"];
echo $tokenobject["apntoken"]."\n";
}

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

Zend Framework 2 can't get fields from joined tables

I can't get fields from the joined table. Here is my situation, I have two tables called "query" and "region" handeled by two controllers QueryCOntroller and RegionController. From the QueryController I tried to join the "query" to "region". to get the name of "query"'s "region"'s name in a view file but I can't get the desired field
public function fetchMine($myid)
{
$sql = new Sql( $this->tableGateway->adapter ) ;
$where = new Where() ;
$where->equalTo('agent_id', $myid) ;
$select = $sql->select() ;
$select -> from ( $this->tableGateway->getTable() )
-> join ( 'region' , 'query.agent_id = region.id')
->columns(array('*'))
-> where( $where ) ;
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}
in my Module.php, getServiceConfig()
'Management\Model\QueryTable' => function($sm) {
$tableGateway = $sm->get('QueryTableGateway');
$table = new QueryTable($tableGateway);
return $table;
},
'QueryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Query());
return new TableGateway('query', $dbAdapter, null, $resultSetPrototype);
},
try:
public function fetchMine($myid)
{
$select = new Select ();
$select->from ( $this->tableGateway->getTable() );
$select->join ( 'region' , 'query.agent_id = region.id' , Select::SQL_STAR , Select::JOIN_LEFT )
$select->where( array( 'agent_id'=>$myid ) );
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}
then you must extends Query from Region for getting all attributes of query and region,
Query.php:
use Management\Model\Region;
class Query extends Region
{
//...
}
The Query class must have attribute has the same name of region name in region table
if you want to use another name just use sql alias
if you want to add more attributes from region table you must add them all in Query class

How can I UPDATE Table A in MySQL joining another table?

I have a stats table that has a user_id.
I have a users table with an id that corresponds to the above user_id. I also have an employee flag in the users table.
I want to update all records in the stats table where the user_id is not that of an employee.
Ideally, I'd like to do this via the CodeIgniter Active Record, but I'm fine with a raw query as well.
Thanks!
EDIT My attempt
if($employee == false) {
$this->db->where('(default_profiles.opid = 0 OR default_profiles.opid IS NULL)');
} else {
$this->db->where('default_profiles.opid > 0');
}
$this->db->join('weekly_stats', 'default_weekly_stats.user_id = default_profiles.user_id');
$this->db->update('default_weekly_stats', $data);
However, this just yields:
UPDATE `default_weekly_stats` SET `rank` = 1 WHERE `default_weekly_stats`.`week` = '1' AND `default_weekly_stats`.`correct_picks` = '4' AND (default_profiles.opid = 0 OR default_profiles.opid IS NULL)
Haven't tried it but maybe it should be like this:
$this->db->where_not_in('users.employee_flag', '0')->join('users', 'users.user_id = stats.user_id')->update('stats', $data);
EDIT: ( based on #dianuj answer )
$this->db->set('rank', $rank );
if($employee == false) {
$this->db->where('(default_profiles.opid = 0 OR default_profiles.opid IS NULL)');
} else {
$this->db->where('default_profiles.opid > 0');
}
$this->db->update('weekly_stats ON default_weekly_stats.user_id = default_profiles.user_id');
update stats s
inner join users u on u.id = s.user_id
and u.employee = 0
set some_column = 'some_value'