How to get the last insert ids from laravel 4 - php

I am using laravel 4. I have a table called documents. I am inserting data in the Document table using Document::insert() function.
My code is given below
$statuses = array();
foreach($content as $i){
array_push($statuses, array(
'user_id' => $user->id,
'document' => $i->text
));
}
$users = Document::insert($statuses);
Now I want to get the insert ids. But the $users variable only gives me a boolean variable called true. How can I get the insert ids.

Use insertGetId()
If the table has an auto-incrementing id, use insertGetId to insert a
record and retrieve the id
Code Snippet
$id = DB::table('Document')->insertGetId($yourarray);
Note: When using PostgreSQL the insertGetId method expects the
auto-incrementing column to be named "id".

Related

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

Laravel 5 save to database and return id

I'm trying to use the eloquent save whilst returning the id of the tuple using
$var=$data->save();
Then trying to return the primary key.Now my primary key is called company_id but when i run:-
$id=$data->company_id
It throws an error saying
column 'id'doesnt exist in the company table.
why does company_id get renamed to id.
place it in your model
protected $primaryKey = 'company_id';
Use insertGetId method to insert a record and then retrieve the ID
here is the example
$id = DB::table('tableName')->insertGetId(
['name' => $request->input('name'),
'address'=> $request->input('address')]
);
print_r($id);

Laravel 5.2 query builder insert method not working

I´m using Laravel 5.2 and I`m using query builder for insert data
DB::table('table')->insert(['field1' => $data['data1'], 'field2' => $data['data2'], 'field3' => $data['data3']]);
this is the controller code
$model = new Model();
$data = array( 'data1'=>$var1, 'data2'=>$var2, 'data3'=>$var3) );
$save = $model->save_data( $data );
I don`t have any errors but data is not saved in the db.
I use in the same model different method query builder methods like update and get and both works fine.
The table have auto increment id data1 is int, data2 is int and data3 is varchar(255)
the values in the array are parsed to the correct data type.
I was making a mistake, the order of the columns of the table must be the same as the order of the insert, I assumed that since the array has the name of the field and its value, the order did not matter.

Kohana 3 ORM: How to get data from pivot table? and all other tables for that matter

I am trying to use ORM to access data stored, in three mysql tables 'users', 'items', and a pivot table for the many-many relationship: 'user_item'
I followed the guidance from Kohana 3.0.x ORM: Read additional columns in pivot tables
and tried
$user = ORM::factory('user',1);
$user->items->find_all();
$user_item = ORM::factory('user_item', array('user_id' => $user, 'item_id' => $user->items));
if ($user_item->loaded()) {
foreach ($user_item as $pivot) {
print_r($pivot);
}
}
But I get the SQL error:
"Unknown column 'user_item.id' in
'order clause' [ SELECT user_item.*
FROM user_item WHERE user_id = '1'
AND item_id = '' ORDER BY
user_item.id ASC LIMIT 1 ]"
Which is clearly erroneous because Kohana is trying to order the elements by a column which doesn't exist: user_item.id. This id doesnt exist because the primary keys of this pivot table are the foreign keys of the two other tables, 'users' and 'items'.
Trying to use:
$user_item = ORM::factory('user_item', array('user_id' => $user, 'item_id' => $user->items))
->order_by('item_id', 'ASC');
Makes no difference, as it seems the order_by() or any sql queries are ignored if the second argument of the factory is given.
Another obvious error with that query is that the item_id = '', when it should contain all the elements.
So my question is how can I get access to the data stored in the pivot table, and actually how can I get access to the all items held by a particular user as I even had problems with that?
Thanks
By default, all of Kohana's ORM models expect the table's primary key to be 'id.' You need to set $_primary_key in your model to something else.
$user_item = ORM::factory('user_item', array('user_id' => $user, 'item_id' => $user->items));
I think you need to provide a single item_id value for this to work, not an array of objects.
Also, to find all entries for a single user you should be able to do this:
$user_items = ORM::factory('user_item', array('user_id' => $user));
Does that answer your question?

Categories