Using same id for multiple rows using codeigniter - php

I have a table with three fields
id (primary key / auto incremented)
product_name
group_id
my problem is when i insert multiple rows through form the whole group of rows should get same groupId & it should be incremented by 1 at the time of submission as there can be many users submitting the form at the same time. I dont know how to do it. Please help.
my model
function get_last_group_id() {
$this->db->select('group_id');
$this->db->from('mytable');
$this->db->order_by('group_id', 'DESC');
$this->db->limit('1');
$query = $this->db->get();
return $query->result();
}
function save_rows($ids,$product_names,$group_ids){
$this->db->trans_begin();
$ndx=0;
foreach($ids as $id){
$data = array(
'id' => $id,
'product_name' => $product_names[$ndx],
'group_id' =>$group_ids[$ndx],
$this->db->insert("product_details",$data);
$this->db->update($this->table);
$ndx++;
}

There is no need to make seperate function for getting group id and set id field also if that is auto incre
function save_rows($ids,$product_names){
$this->db->trans_begin();
$ndx=0;
$group_id = $this->db->select("MAX(group_id) as group_id")
->from("mytable")
->get()->row_array();
foreach($ids as $id){
$data = array(
'product_name' => $product_names[$ndx],
'group_id' =>$group_id['group_id']+1,
);
$this->db->insert("product_details",$data);
$ndx++;
}

You can create a new table say 'groups'
fields: id(Auto Increment) and group_name (varchar)
generate group name randomly.
Then before inserting products create a new group then you will get a new groupID that will be unique.
Then using that groupID you can carry your option forward

Related

Insert multiple rows Codeigniter

I'm trying to insert multiple dynamic rows to a table,
I have two tables.. 'students' and 'studentextend'..
with two primary keys (studentID in 'students) and (studentextendID in 'studentextend'), and table 'studentextend' has a field 'studentID' that is the primary key in 'students' table.
What i'm trying to do is, insert multiple rows dynamically into table 'studentextend', but each row has to have the same studentID and It's different from 'studentextendID' which is Auto increment, In other words, trying to assign multiple dynamic subject fields to one student.
But it's not inserting anything.
Controller:
$data=$this->input->post();
for($i=0; $i<sizeof($data['subject']); $i++) {
$studentExtendArray[] = array(
'studentID' => $studentID,
'subject' => $this->input->post('subject[$i]')
);
}
$this->studentextend_m->insert_batch_studentextend($studentExtendArray);
Model
public function insert_batch_studentextend($array) {
$id = parent::insert_batch($array);
return $id;
}

Foreign key issue while inserting data in child table Laravel

I am trying to insert data in orders table and then save order details in order_details table. Following is the code that I'm trying
$order = Order::create($request->all());
$order->order_detail()->insert($request->order_detail); //$request->order_detail is an array
In my model I have provided relationships
Order Model
public function order_detail(){
return $this->hasMany(OrderDetail::class, 'order_id');
}
Order Detail Model
public function order(){
return $this->belongsTo(Order::class,'order_id');
}
but it returns me General error: 1364 Field 'order_id' doesn't have a default value as order_id is a foreign key in order_details table
How can I do it without giving order_id manually
I am going to assume that $request->order_detail is an array of many order_details.
The problem with insert is that you are not using Eloquent but the query builder, therefore Laravel is not able to fill the order_id by itself, if you use createMany instead it will be able to do so:
$order = Order::create($request->all());
$order->order_detail()->createMany($request->order_detail);
From the docs:
You may use the createMany method to create multiple related models:
$post = App\Post::find(1);
$post->comments()->createMany([
[
'message' => 'A new comment.',
],
[
'message' => 'Another new comment.',
],
]);
Since your $request->order_detail isn't gonna contain order_id. You can take that from the newly created $order.
$order = Order::create($request->all()); // upon create, you can access the order_id by doing $order->id
$orderDetails = [];
foreach($request->order_detail as $details) {
$orderDetails[] = [
array_merge($details, ['order_id' => $order->id]);
];
}
$order->order_detail()->insert($orderDetails);
Sounds like a database issue. The column order_id has AUTO_INCREMENT, meaning it would generate a number upon insert.
Try inserting with phpMyAdmin to see whether AUTO_INCREMENT works. Or use SHOW TABLE STATUS and check AUTO_INCREMENT.

Problem with populating database column with seeding in Laravel

I need to populate my database column from seeding. I have 'interested_in' column in user_profiles table and I need to populate it with according id from 'value_id' column from user_interests table. Both user_profiles and user_interests table are connected to users table ('user_id' column is in both tables). So if the value of 'value_id' column is for example 1 it needs to be 1 in 'interested_in' column, I need help on how to populate that 'interested_in' column from seeders. 'value_id' column is already populated. Here are my tables and example data and my code so far but it doesn't work currently, it shows 'Array to string conversion' error.
user_interests table
user_id field_id value_id
1 1 1
user_profiles table
id user_id interested_in
1 1 and here needs to be 1, to associate value_id (1) from user_interests table
UserProfileTableSeeder.php
class UserProfileTableSeeder extends Seeder
{
use ChunkSeeder;
public function run()
{
$users = User::all()->pluck('id');
$user_interests = DB::table('user_interests')->select('value_id')->where('field_id', 1)->get();
$user_interests_values = $user_interests->pluck('value_id')->toArray();
$seed = [];
foreach ($users as $userId) {
$seed[] = factory(UserProfile::class)->make(
[
'user_id' => $userId,
'interested_in' => $user_interests_values, // Shows array to string error!!!
]
)->toArray();
}
$this->seedChunks($seed, [UserProfile::class, 'insert']);
}
}
That's why $user_interests_values is an array as you can see in this line (at the end):
$user_interests_values = $user_interests->pluck('value_id')->toArray();
Try in the factory to change $user_interests_values to current($user_interests_values) or probably $user_interests_values['id'] or whatever.
PS: I am not really sure what's inside $user_interests_values, you can see it with a dd() and running the migration then (don't worry, the migration won't be successful because of the dd() and you will be able to run it later again until it finishes properly.
By the way, I recommend you to do something more legible than you did in your rum() method. I mean, something like this:
$interest = factory(UserInterests::class)->create();
factory(UserProfiles::class, 20)->create([
'interest' => $interest->id,
]);

fetch and push the data in new table

I have the table 'project','user' and 'role_mapping'.I want to to fetch the project_owner_id from the project table and push the user_id which is fetched from user table and role_id=1 in role_mapping table.one project owner has multiple project.so I want to restrict duplicate entry. I want to do it in laravel controller controller.
project table
project_id project name project_owner_id
1 DEC01
2 DEC02
3 DEC01
user table
id user_string
1 DEC03
2 DEC01
3 DEC02
role_mapping table
user_id role_id
2 1
3 1
$heads = DB::table('project')
->join('users', 'project.project_owner_id', '=', 'users.user_string')
->select('project.project_owner_id','users.id as user_id')->get();
foreach($heads as $head){
print_r($head->project_owner_id);
print_r($head->user_id);
}
The below query fetched project owner id and user_id.How to push the value in role_mapping table
Try to refer to this one, using Attach, Detach in laravel : http://kaloraat.com/questions/laravel-attach-detach-and-sync-methods
Hope this helps :)
Like this way
Assuming your model name as MappingTable
foreach($heads as $head){
$mapTable = new MappingTable();
$mapTable->user_id = $head->user_id;
$mapTable->role_id = $head->project_owner_id;
$mapTable->save();
}
OR alternatively you can pass $data array like this
$data = array(
array('user_id'=>$head->user_id, 'role_id'=> ),
array('user_id'=>$head->user_id, 'role_id'=> $head->project_owner_id),
//...
);
MappingTable::insert($data); // Eloquent
DB::table('role_mapping table')->insert($data); // Query Builder

CodeIgniter/PHP/MySQL: Retrieving data with JOIN

I'm new to PHP/MySQL and super-new to CodeIgniter..
I have information in many MySQL tables. I want to retrieve it with JOIN where the tables primary keys are equal to $variable... How can I do it and get all the fields without the primary key field???
What I'm doing now is this (only two tables joined here):
function getAll($id) {
$this->db->select('*');
$this->db->from('movies');
$this->db->join('posters', 'movies.id= posters.id');
// WHERE id = $id ... goes here somehow...
$q = $this->db->get();
if ($q->num_rows() == 1) {
$row = $q->row();
$data = array(
'id' => $row->id,
'title' => $row->title,
'year' => $row->year,
'runtime' => $row->runtime,
'plotoutline' => $row->plotoutline,
'poster_url' => $row->poster_url
);
}
$q->free_result();
return $data;
id (PK), title, year, runtime and plotoutline are columns from the first table and poster_url is a field from the second table. The second table also contains an ID (PK) column that I don't want to Retrieve because I already have.
Jon is right. Here's an example:
$this->db->select('movies.id,
movies.title,
movies.year,
movies.runtime as totaltime,
posters.poster_url');
$this->db->from('movies');
$this->db->join('posters', 'movies.id= posters.id');
$this->db->where('movies.id', $id);
$q = $this->db->get();
This will return objects that have ->id, ->title, ->year, ->totaltime, and ->poster_url properties. You won't need the additional code to fetch the data from each row.
Don't forget, if the Active Record syntax gets a little unwieldy, you can use full SQL queries and get the same results:
$sql = "SELECT movies.id,
movies.title,
movies.year,
movies.runtime as totaltime,
posters.poster_url
FROM movies
INNER JOIN posters ON movies.id = posters.id
WHERE movies.id = ?"
return $this->db->query($sql, array($id))->result();
Both forms will ensure that your data is escaped properly.
CodeIgniter Active Record
Query Binding in CodeIgniter
An asterisk will return all the fields. To return a subset of these, i.e. all fields apart form the repeated id field, simply list the columns which you require rather than use '*'.
It is often a good idea to not use asterisk anyway. In the future of the app, someone may add a large field to the table which will be surplus to your requirements, and will slow your queries.
Simply put with method chaining:
$this->db->select('*')
->from('movies')
->join('posters', 'movies.id= posters.id')
->where('movies.id', $id)
->get();
$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();

Categories