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
],
]);
Related
I have two tables: (Table A & TableB).
Table A = id(primary), name, email
Table B = user_id(foreign(id)), column1, column2
What I need to do is:
Insert a row in Table A.
Verify the insertion.
Insert row in Table B & store Table A (id) in Table B (user_id).
Currently, I'm handling it like the following.
// Create a row in Table A
$createUser = UserModel::create($userData);
// Verifying insertion of the by checking if id is set
if (isset($createUser['id'])) {
$adminData = [
'name' => $info['adminName'],
'user_id' => $createUser['id'], // insert into user_id
'email_address' => $info['adminEmail'],
'contact_number' => $info['adminNumber'],
];
$createAdmin = AdminsModel::create($adminData);
}
I'm looking for a better way for multiple chained tables to avoid an if-else ladder.
There is nothing wrong with what you are doing. But you can also use eloquent relationships.
First define this method in the UserModel.
/**
* Get the admin associated with the user.
*/
public function admin()
{
return $this->hasOne(AdminsModel::class);
}
And use it like so
$createUser = UserModel::create($userData);
$createUser->admin->create([
'name' => $info['adminName'],
'email_address' => $info['adminEmail'],
'contact_number' => $info['adminNumber'],
]);
When a user create an item, on my controller i need to send 2 SQL Query.
The first is easy to do:
$data = array(
'author' => $this->input->post('author'),
'name' => $this->input->post('name'),
);
$this->item_model->insertItem($data);
But on my second query, i need to recover, to find the ID of the query showing just before.
For example:
$data = array(
'user_id' => $_SESSION['user_id'],
'item_id' => ????,
);
$this->item_model->insertItem($data);
Thanks
For fetching the last inserted ID of variable $item_id in the same transaction of your controller, you can get the ID of record in the same session as follows:
$item_id = $this->db->insert_id();
I am trying to pull record from a table using the following code
$userId = Yii::$app->user->id;
$lists = PromoLists::findAll(['user_id' => $userId, 'list_type' => 'custom']);
which outputs a query like below
select * from promo_lists where user_id ='$userId' and list_type='custom'
But i am unable to find any thing in the documentation that would help me achieve it with the following condition.
select * from promo_lists where user_id ='$userId' and list_type='custom' and status!='deleted'
as the status is an ENUM field and there are 4 different status
'active','pending','rejected','deleted'
currently i used the following approach
PromoLists::findAll(['user_id' => $userId, 'list_type' => 'custom', 'status'=>['active','pending','rejected']]);
which outputsthe following query
select * from promo_lists where user_id ='$userId' and list_type='custom' and status in ('active','pending','rejected')
which somehow achieves the same thing but this query would need to be edited every time when there is a new status type added to the table column status.
i know i can do this by using PromoLists::find()->where()->andWhere()->all()
but how to check with != / <> operator using findAll().
Simply like this:
PromoLists::find()->where(['and',
[
'user_id' => $userId,
'list_type' => 'custom',
],
['<>', 'status', 'deleted'],
])->all();
Using operator format in condition
http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#operator-format
PromoLists::find()
->andWhere([
'user_id' => $userId,
'list_type' => 'custom',
['!=', 'status', 'deleted']
])
->all();
I have a field in database. It's type is enum and it looks like
enum('NO ANSWER', 'ANSWERED', 'BUSY').
I need to put this values into dropdown. How can I write query in cakephp?
I tried:
$result = TableRegistry::get('Calls')->find('list', ['valueField' => 'disposition'])->distinct('disposition')->toArray();
But it returns
[
(int) 1 => null,
(int) 77 => '',
(int) 64 => 'NO ANSWER',
(int) 65 => 'ANSWERED',
(int) 72 => 'BUSY'
]
but I need something like this:
[
(int) 1 => 'NO ANSWER',
(int) 2 => 'ANSWERED',
(int) 3 => 'BUSY'
]
I need to put this values into dropdown
Unless the enum values are going to change frequently (and if the are, why would you use an enum..) just put the array of data you need somewhere:
$options = [
'NO ANSWER' => 'NO ANSWER',
'ANSWERED' => 'ANSWERED',
'BUSY' => 'BUSY'
];
And then use it:
echo $this->Form->select('field', $options);
Note that the key in $options is what will be submitted, the value is what will be displayed. More info about the select method is in the documentation.
I found this answer somewhere on SO, but I couldn't find it again. You can do this:
$cols = $this->Model->query("show columns from table_name like 'enum_column_name'")
$enum = explode(',', substr(str_replace(array("'", "(", ")"),'',$cols[0]['COLUMNS']['Type']), 4));
$options = array_combine($enum, $enum);
Then in your form, you can use the end of AD7six's answer and add:
echo $this->Form->select('field', $options);
The problem is that the values of enum are defined in the create table, they are not a piece of data available when you query your table's data. How can I get enum possible values in a MySQL database? SO topic describes how to get the values of the enum through a php code. Just make sure that you reassign the keys for the enum values so that the keys start from 1, and not from 0 (0 stands for empty value).
I am retrieving data:
$mydata = $this->ProductList->find('all', array('order' => 'rand()', 'conditions' => array('name' => 'we love')));
I have set up a HABTM relationship to the Product model. As you can see, I am fetching all products in the 'we love'-list. Now, I want those Products I am retrieving to be randomised. But they are not, instead the MySQL is randomised on the ProductList model as you can see in the SQL. Why is that? How can I get the random fetch on the Products instead?
Resulting MySQL query:
SELECT `ProductList`.`id`, `ProductList`.`name` FROM `database`.`product_lists` AS `ProductList` WHERE `name` = 'we love' ORDER BY rand() ASC
SELECT `Product`.`id`, `Product`.`category_id`, `Product`.`name`, `Product`.`price`, `Product`.`description`, `ProductListsProduct`.`product_list_id`, `ProductListsProduct`.`product_id` FROM `database`.`products` AS `Product` JOIN `database`.`product_lists_products` AS `ProductListsProduct` ON (`ProductListsProduct`.`product_list_id` = 3 AND `ProductListsProduct`.`product_id` = `Product`.`id`)
EDIT:
There are so many different ways to approach this; to get a random product from a user's product list. You could do it with PHP - just find all of the products and then use rand() to pick on from the returned array. You could set a Model query condition. The list goes on...
I would probably create an alias to the Product model in ProductList called RandomProduct. You could set the query for the retrieved product when you set the relationship:
public $hasMany = array(
'RandomProduct' => array(
'className' => 'Product',
'foreignKey' => 'product_list_id',
'order' => 'Rand()',
'limit' => '1',
'dependent' => true
)
);
You can then use the containable behavior so that this model is only retrieved when you need it. (You wouldn't need to do this if recursive finds are greater than -1, but I usually do that as best practice so that my models only query for the data that they need.) The following would return any ProductList called 'we love' and a "random" product associated with that list.
$mydata = $this->ProductList->find(
'all',
array(
'conditions' => array(
'name' => 'we love'
)
),
'contain' => array(
'RandomProduct'
)
);