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
Related
I have a function that retrieve values from database as json.I need some data from database and a value of SUM for certain column.When i not retrieve SUM from those value i get all required data but when i also include SUM function to get total of values from certain column i get only single object of value
MODEL
public function search_tickets($data){
$ticketDate = $data['ticket_date'];
$ticketBus = $data['ticket_bus'];
$ticketAgentId = $data['agent_id'];
$user = $this->db->select("
CONCAT_WS(' ', tp.firstname, tp.lastname) AS passenger_name,
tb.seat_numbers AS seat_number,
tb.id_no AS ticket_number,
fr.reg_no AS bus_number,
DATE_FORMAT(ta.start_date, '%d/%m/%Y') as ticket_date,
tb.price AS fare_paid,
tb.pickup_trip_location AS boarding,
tb.drop_trip_location AS dropping,
SUM(tb.price) AS total_fare
")
->from('tkt_booking AS tb')
->join('tkt_passenger AS tp', 'tb.tkt_passenger_id_no = tp.id_no' ,'full')
->join('trip_assign AS ta', 'ta.id = tb.trip_id_no' ,'full')
->join('trip_route AS tr', 'tr.id = tb.trip_route_id','full')
->join('agent AS a', 'a.agent_id = tb.agent_id','full')
->join('fleet_registration AS fr', 'fr.id = ta.fleet_registration_id','full')
->where('ta.start_date', $ticketDate )
->where('fr.reg_no', $ticketBus )
->where('tb.agent_id', $ticketAgentId )
->get()
->result();
return $user;
}
CONTROLLER
public function searchTickets(){
$data = $_POST;
$ticket=$this->booking_model->search_tickets($data);
if($ticket){
$result = array('tickets'=>$ticket);
} else {
$result = NULL;
}
print json_encode($result);
}
You should GROUP BY passenger id to get the total sum for each passenger:
$this->db->group_by('tb.tkt_passenger_id_no');
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();
i create a query like below but always error Not unique table/alias although i add alias for askPo in every relation model.
$query = AskPolicy::find();
$query-> JoinWith(['askPos'])
->where(['askPolicy.id' => 'askPos.id_policy'])
->innerJoinWith(['askPos.askGoods'])
->andWhere('ask_po.id = ask_goods.id_po')
->innerJoinWith(['askTransports'])
->andWhere('ask_policy.id = ask_transport.id_po')
->innerJoinWith(['client'])->andWhere(['id_client'=>Yii::$app->user->identity->id_client])->all();
below i have add alias
model a :
public function getAskPos()
{
return $this->hasMany(\frontend\modules\ask_marine_cargo\models\AskPo::className(), ['id_policy' => 'id'])->from(AskPo::tableName() . ' askPo1');;
}
model b :
public function getPo()
{
return $this->hasOne(\frontend\modules\ask_marine_cargo\models\AskPo::className(), ['id' => 'id_po'])->from(AskPo::tableName() . ' getPo');
}
SQL query :
SELECT
ask_goods.name,
ask_po.po_num,
ask_policy.policy_num,
ask_transport.type_transport
FROM ask_policy
INNER JOIN ask_po
ON ask_po.id_policy = ask_policy.id
INNER JOIN ask_goods
ON ask_po.id = ask_goods.id_po
INNER JOIN ask_transport
ON ask_policy.id = ask_transport.id_po;
I am working in Laravel5.4. I have created 3 table's.
User table :
tickets table :
ticket_cc_users table :
Now, I have create relation ship between users and tickets module like below.
User model :
public function tickets()
{
return $this->belongsToMany('App\User', 'ticket_cc_users', 'user_id', 'ticket_id');
}
Ticket model :
public function users()
{
return $this->belongsToMany('App\Models\Tickets\Ticket', 'ticket_cc_users', 'ticket_id', 'user_id');
}
TicketController controller save method :
public function store(Request $request)
{
return $request->all();
$ticket = new Ticket;
$ticket->requester_id = $this->user['id'];
//$ticket->assignee_id = $request->assignee_id;
//$ticket->cc_id = $request->cc_id;
$ticket->type = $request->type;
$ticket->priority = $request->priority;
$ticket->subject = $request->subject;
$ticket->description = $request->description;
$ticket->status = $request->status;
if($request->link)
{
$ticket->link = $request->link;
$ticket->due_date = null;
}
if($request->due_date && $request->due_date !="")
{
$ticket->due_date = date('Y-m-d',strtotime($request->due_date));
$ticket->link = "";
}
if($ticket->save())
{
$ticket->users()->sync($request->cc_id);
foreach($request->ticket_tags as $value){
$tag = new Tag;
$tag->tag_name = $value['text'];
$tag->save();
$ticketTag = new TicketTag;
$ticketTag->tickets_id = $ticket->id;
$ticketTag->tags_id = $tag->id;
$ticketTag->save();
}
$data = Ticket::find($ticket->id);
Mail::to('khyati#infirays.com')->send(new CreateTicket($data));
$response = array(
'success' => true
);
}
return $response;
}
Here, I am going to store data into ticket table. So I need to store cc user data into ticket_cc_user table. So how can I store ticket_id and user_id into this table. Here, I can get multiple user_id. And I am using Eloquent ORM.
Here, It gives an error like SQLSTATE[42S22]: Column not found: 1054 Unknown column '$$hashKey' in 'field list' (SQL: insert into ticket_cc_users ($$hashKey, address, city_id, country_id, created_at, deleted_at, email, firstname, id, introducer_id, is_verified, lastname, phone, signature, state_id, ticket_id, updated_at, user_id, username, userrole_id) values (object:109, , , , 2017-02-10 05:26:01, , nisarg.b#infirays.com, , 26, 1, , , 9999999999, , , 1, 2017-02-14 08:33:18, 0, nisarg, 2))
So,what code should I have to change in save function to store data into ticket_cc_users table?
It seems that belongsToMany() parameters order should be changed. The first and the last(4-th) parameters should be "about" same instance.
UPDATE Also the body of tickets() and users() functions should be exchanged
So try this:
User model :
public function tickets()
{
return $this->belongsToMany('App\Models\Tickets\Ticket', 'ticket_cc_users', 'user_id', 'ticket_id');
}
Ticket model :
public function users()
{
return $this->belongsToMany('App\User', 'ticket_cc_users', 'ticket_id', 'user_id');
}
From Laravel Many To Many Docs:
The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to:
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
public function getInterests($userID) {
$result = $this->tableGateway->select(function (Select $select) use ($userID) {
$select->join('interests', 'users_interests.interest_id = interests.interest_id', array('*'), 'left');
$where = new Where();
$where->equalTo('user_id', $userID);
$select->where($where);
});
return $result;
}
Here is my method. It simply selects all records from users_interests with user_id = $userID and joins the 'interests' table. So far, so good, but when trying to display the fetched results, the fields from the joined table just do not exist. Here is the dump of the $result:
Zend\Db\ResultSet\ResultSet Object
(
[allowedReturnTypes:protected] => Array
(
[0] => arrayobject
[1] => array
)
[arrayObjectPrototype:protected] => Object\Model\UsersInterests Object
(
[settings_id] =>
[user_id] =>
[interest_id] =>
)
[returnType:protected] => arrayobject
[buffer:protected] =>
[count:protected] => 2
[dataSource:protected] => Zend\Db\Adapter\Driver\Pdo\Result Object
(
[statementMode:protected] => forward
[resource:protected] => PDOStatement Object
(
[queryString] => SELECT `users_interests`.*, `interests`.* FROM `users_interests` LEFT JOIN `interests` ON `users_interests`.`interest_id` = `interests`.`interest_id` WHERE `user_id` = :where1
)
[options:protected] =>
[currentComplete:protected] =>
[currentData:protected] =>
[position:protected] => -1
[generatedValue:protected] => 0
[rowCount:protected] => 2
)
[fieldCount:protected] => 6
[position:protected] =>
)
I badly need help on this because I am supposed to finish my project until Sunday. Thanks in advance.
You can use the following to apply left join. $select::JOIN_LEFT instead of 'left'.
public function getInterests($userID) {
$result = $this->tableGateway->select(function (Select $select) use ($userID) {
$select->join('interests', 'users_interests.interest_id = interests.interest_id', array('*'), $select::JOIN_LEFT);
$where = new Where();
$where->equalTo('user_id', $userID);
$select->where($where);
});
return $result;
}
It seems you have a problem in the WHERE clause of the join. This also shows in the error here:
[queryString] => SELECT `users_interests`.*, `interests`.* FROM `users_interests` LEFT JOIN .
`interests` ON `users_interests`.`interest_id` = `interests`.`interest_id`
WHERE `user_id` = :where1
Try this:
$select->from($this->table)
->join('interests', 'users_interests.interest_id = interests.interest_id',
array('*'), 'left');
$where = new Where();
$where->equalTo('user_id', $userID) ;
$select->where($where);
I can not follow your code completely, like here:
$this->tableGateway->select(function (Select $select) use ($userID) {
But, here is a very nice article on this. I think, you can simplify your code a little.
Have you iterated over the resultset? You can see there's two matching rows:
[rowCount:protected] => 2
You have a ResultSet object, but it will not load any of the rows until requested, they are "lazy loaded" when you iterate over the object.
You can force the resultset to get them all for you:
var_dump($resultSet->toArray()); // force load all rows
or iterate over the ResultSet:
foreach($resultset as $row) {
var_dump($row); // each row loaded on request
}
I have written about this before and maybe it will help you as well.
TableGateway with multiple FROM tables