Yii2 DropdownList on relationated tables - yii2

i have 3 tables
Events
*id
*idteacher
Teacher
*id
*person
Person
*id
*name1
*name2
*lastname1
*lastname2
How can i make a Dropdownlist on Events Form that shows the fullname of person but save the idteacher???
<?= $form->field($model, 'idexpositor')->DropdownList(
ArrayHelper::map(TblExpositor::find()->all(),'id','idpersona'),
['prompt'=>'Seleccione el nombre del Expositor']
);?>

You can use a proper query .. like this (adapt the field and column name to your need)
<?= $form->field($model, 'your_field_in_model')->DropdownList(
ArrayHelper::map(TblExpositor::find()->
select('t.id as id, concat(p.nama1, p.name2, p.lastname1, p.lastname2) as name')->
from('Teacher t, Person p')->
where('t.personeid = p.id')->all(),'id','name'),
['prompt'=>'Seleccione el nombre del Expositor']
);?>

Related

Subquery using the same table

I need to make a subquery in the same table to bring me back all the results inside of each id, and print it inside on a while.
$stl = $conn->prepare("SELECT DISTINCT CONCAT(first_name,' ',last_name) AS name, rol FROM USERS WHERE id = :id AND rol = 1 ORDER BY id ASC");
$stl->bindParam(':id', $id, PDO::PARAM_INT);
$stl->execute();
echo '<table><thead><tr><th>MASTER</th><th>SUPERVISOR</th><th>NOOB</th></thead>';
echo '<tbody>';
while($row = $stl->fetch(PDO::FETCH_ASSOC)) { ?>
echo '<tr><td>'.$row['name'].'</th><th>'.$row['name'].'</th><th>'.$row['name'].'</td></tr>';
<?php }
echo '</tbody></table>'; ?>
This query print the result where rol = 1, but I need to show rol = 2 and rol = 3 too in the same result order (all users in rol 1, in rol 2 and in rol 3) inside of table, I think that I need a subquery in the same table (2 times more).
I need show the results like this:
MASTER
SUPERVISOR
NOOB
JOE BRUT
PEP ARIOLA
ANDY CHOLS
MAT GREEN
CARLA DIAZ
JOSE ZAVALA
There are fan post where not all the user role commented, so I don't want to show blank spaces...
Per example:
MASTER
SUPERVISOR
NOOB
JOE BRUT
PEP ARIOLA
JOSE ZAVALA
CARLA DIAZ
MAT GREEN
Best regards!

Develop picture album using codeigniter, query to select images?

I am developing a web application using codeigniter.In there i am making a part to show images like in facebook as this screenshot.
For that i have created two database table.One to keep album names with user id.One for to keep images names with album id.Here i am providing the screenshot of two table.
I have lot of albums in the album table for one user.now i have entered only one data to this table just for test.how can i select only one image from one album to create album view like in Facebook wish i have shown in the top of this question as screenshot.I create a query like this in the model to select image.
$username=$this->session->userdata('username');
$this->db->select('id');
$this->db->where('email',$username);
$query=$this->db->get('user');
foreach ($query->result() as $row)
{
$user_id= $row->id;
}
$this->db->select('*');
$this->db->where('album_images.user_id',$user_id);
$this->db->from('album_images');
$this->db->join('album', 'album.id = album_images.album_id');
$query = $this->db->get();
return $query->result();
How can improve this code to select only one image from each album and pass all the details of that image such as image id, album_id,album_name,image_name to the view?
try this
$this->db->select('uai.album_id, ua.album_name, uai.id as image_id, uai.image_name');
$this->db->from('user as u');
$this->db->join('album as ua', 'ua.user_id = u.id', 'left');
$this->db->join('album_images as uai', 'uai.user_id = u.id AND uai.album_id = ua.id', 'left');
$this->db->where('u.email',$this->session->userdata('username'));
$this->db->group_by('uai.user_id, uai.album_id');
$this->db->order_by('ua.album_name ASC');
$query = $this->db->get();
return ($query->num_rows() > 0) ? $query->result() : false;
Output will like following
Array
(
[0] => stdClass Object
(
[album_id] => 1
[album_name] => Apple
[image_id] => 1
[image_name] => Apple1.jpg
)
[1] => stdClass Object
(
[album_id] => 2
[album_name] => Orange
[image_id] => 3
[image_name] => Orange1.jpg
)
)
image_name will return one image from album_images table
ex. `[image_name] => Apple1.jpg` from (Apple1.jpg,Apple2.jpg,Apple3.jpg ..etc)

Yii2 Select2 and related tables

I have two related tables. For example,
tbl_one
id
name
tbl_second
id
id_tblone(this is fk)
name
For example:
tbl_one
id: 1
name: input one
tbl_second
id: 1
id_tblone: 1
name: data one
id: 2
id_tblone: 1
name: data two
Select will show:
input one
input two
I want to use Kartik's select in a form that will save new data in tbl_second. So I need Select2 to select id_tblone (or id from tbl_one) and his according name. User needs to select, let's say proper category (from first table - I have fk that relates those two tables) and add some new data under that category in second table.
What would be proper way to do this?
Edit: i have managed so far to show proper names under proper id_tblone, but it saves data with value null in id_tblone column in my second table
In controller:
$query = array();
$query = (new \yii\db\Query())
->select(['id', 'name'])
->from('tbl_one')
->leftJoin('tbl_second', 'tbl_second.id_tblone = tbl_one.id')
->all();
in view:
$data = ArrayHelper::map($query,'name', 'id');
echo Select2::widget([
'name' => 'newname',
'data' => $data,
'pluginOptions' => [
'allowClear' => true
],
]);

I do not understand joining tables

I'm using Cake version 2.5.4
I have two tables.
A call arbols which consists of the following fields:
id (int 11)
nombre (varchar (255)
especie:id (int 11)
The second table called fotos consists of the following fields:
id (int 11)
foto (varchar 255)
foto_dir (varchar 255)
arbol_id (int 11)
Although the Arbol model is related to the Especie model,
I leave it aside to the latter because it is not a reason for consultation.
The Arbol Model has a hasMany relationship with the Foto model.
In the Arbol model I have the following:
public $hasMany = array(
'Foto'=> array(
'className' => 'Foto',
'foreignKey' => 'arbol_id',
'dependent' => true
)
);
In the Foto model I have the following:
public $belongsTo = array(
'Arbol'=> array(
'className'=>'Arbol',
'foreign_key'=>'arbol_id'
)
);
Now, inside ArbolsController in public function view ($ id = null)
I want to do the following SQL query:
SELECT * FROM arboles as a join fotos as f on a.id=f.arbol_id
So I return all the photos related to an id of a particular tree passed as parameter in view
If this query is done using MySQL
$registros=mysqli_query($conexion," select * from arboles as a join fotos as f on a.id=f.arbol_id")
it works.
But if I want to do it using the query method in such ways:
$registros = $this->Arbol->query("select * from arboles as a INNER JOIN fotos as f ON a.id=f.arbol_id");
$registros = $this->Arbol->query("select * from arboles as a INNER JOIN fotos as f ON a.id=f.arbol_id");
It does not work
Reading the Cookbook I see there is a way to make joins.
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html
I dont understand her
I would appreciate it if you can explain it to me.
From already thank you very much!
You shouldn't be using the query method directly if you can avoid it.
What you can do is using a standard find, joining your tables with containable (or linkable).
Something like this should work:
$registros = $this->Arbol->find('all', array(
'contain' => 'Foto'
));
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
There is another way by you can join the tables in cakephp i.e customized joins
Create an array of tables whom you want to join, such as
$joins = array(
array(
'table' => 'fotos',//Table name
'alias' => 'Foto', //Model name
'type' => 'INNER', // type of join
'conditions' => array(
'Arbol.id = Foto.arbol_id'
) //Condition for join
)
);
$this->Arbol->find('all', array(
'joins' => $joins,
'conditions'=> array(Arbol.id => $id),
'fields' => array()
))
This will return all the photos information related to an id

Another "need to pull data from two tables in cakephp"

Ok, I have two tables, users and units. 'Unit' belongsTo 'User', and 'User' hasMany 'Unit'. I would like to access all of the data from my units table, and append SOME of the data from my users table for the view. Here is my controller code:
public function condos() {
$u=$this->User->Unit->find('all', array('conditions'=>array('type'=>'condo', 'active'=>1)));
$this->set('allcondos', $u);
}
I have two models, User and Unit, here is the code for them:
from unit.php:
class Unit extends AppModel {
var $name='Unit';
var $belongsTo=array(
'User'=>array(
'className'=>'User',
'foreignKey'=>'user_id'
) );
}
and from user.php:
class User extends AppModel {
var $name='User';
var $hasMany=array(
'Unit'=>array(
'className'=>'Unit',
'foreignKey'=>'user_id'
) );
}
Here is my view code:
<?php foreach ($allcondos as $condo) { ?>
<section class="listings">
<figure>
<img src="<?php echo $condo['Unit']['photo1']; ?>" />
</figure>
<h1><?php echo $condo['Unit']['complex'], ' ', $condo['Unit']['unitnum']; ?></h1>
<h2><?php echo $condo['Unit']['city']; ?>, <?php echo $condo['Unit']['state']; ?> | (<?php echo $condo['User']['area_code']; ?>)<?php echo $condo['User']['exchange'];?>-<?php echo $condo['User']['sln'];?></h2>
<p><?php echo $condo['Unit']['unit_desc']; ?></p>
</section>
<?php } ?>
I have a problem with the call to $condo['User']['any_field'] as it returns zero 'User' data. (It returns the 'Unit' data just fine). I don't know how to access both tables, obviously.
If I debug $allcondos in the view, it looks like this:
Array
(
[0] => Array
(
[Unit] => Array
(
[id] => 1
[user_id] => caribeincrentals
[additional fields] ...
)
[User] => Array
(
[id] =>
[user_id] =>
[additional fields] ...
)
)
[1] => Array ...
)
$this->Unit->find('all', array(
'conditions' => array(
'type' => 'condo',
'active' => 1,
),
'contain' => array(
'User',
),
));
Use containable to get related data. You can use conditions within that contain as well to restrict what information you want.
http://book.cakephp.org/view/1323/Containable
Without your database details, it is tough to say exactly what is going on. However, you seem to be using a string value as the foreignKey that links your 2 models together. This is a bad idea.
I suggest changing the user_id fk to an int datatype that references the id key column on the Users table (well, assuming that id is an autoincrementing integer value).
It's tough to say if this is the exact problem, but it's definitely worth checking out and will help you avoid some other headaches in the future.
UPDATE
If you structure your tables according to Cake conventions, most of the associative work will be done for you. Here's how I would do it:
Users table ('users'):
id primary key (int)
User model:
$hasMany = array( 'Unit' );
Units table ('units'):
id primary key (int)
user_id corresponds to id in users table
Unit model:
$belongsTo = array( 'User' );
If you set your tables & models up like that, Cake will automatically associate 'user_id' in the units table with 'id' in the users table.