Codeigniter: Know AI ID of query - mysql

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();

Related

Can change id to custom_id when insert data from a table to another?

I am trying to insert data from a table to another but I want, when I transfer this data to other table ids to change. For example(Table1 ID=1001 -> Table2 custom_id=custom_1001). I'm trying to do it in Laravel.
This is how I transfer data from table1 to table2. But I don't now how to add 'custom_' before id on table2
$qry = DB::table('table1')->get();
foreach($qry as $key => $data_in) {
DB::table('table2')->insert([
"custom_id" => $data_in->id,
"status" => $data_in->status
]);
}
You can use mysql CONCAT function to add prefix
$qry = DB::table('table1')
->selectRaw('CONCAT("custom_",id) AS custom_id')
->addSelect('status')
->get();
foreach($qry as $key => $data_in) {
DB::table('table2')->insert((array)$data_in);
}
first make custom_id string then just do something like this:
$qry = DB::table('table1')->get();
foreach($qry as $key => $data_in) {
DB::table('table2')->insert([
"custom_id" => "custom_" . $data_in->id,
"status" => $data_in->status
]);

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
],
]);

Not equal condition with findAll()

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();

Laravel Get Record ID from Update Query

For this update query, I'm trying to get the id after I run it.
$results = DB::table('testDB123.users')
->where('fbID', '=', $x['id'])
->update([
'updated_at' => $x['currDate'],
'fbFirstName' => $x['firstName'],
'fbLastName' => $x['lastName']
]
);
Tried this with no luck $results->id
Is there anything similar to insertGetId for update queries?
$id = DB::table($table1)->insertGetId([...])
update() method doesn't return an object, so you have two options:
Option 1
Use updateOrCreate():
$user = User::updateOrCreate(['fbID' => $x['id']], $dataArray);
$id = $user->id;
Option 2
Get an object and update it:
$user = User::where('fbID', '=', $x['id'])->first();
$user->update($dataArray);
$id = $user->id;

CakePHP model associations - Random order on retrieve of associated model for HABTM

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