Foreign key issue while inserting data in child table Laravel - php

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.

Related

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

Integrity constraint violation: 1452 Cannot add or update a child row in Laravel 5.2

I get an error when i try to insert a role.I have found some solution of this issue in StackOverFlow but all those does not solve my problem.
I am trying to get id from roles table into roleID column of user_roles table.Here i am using Query Builder of Laravel 5.2.
public function store(Request $request)
{
//
$role = [];
$role['role'] = $request->input('role');
$data= Role::create($role);
$id= $data->id;
DB::table('user_roles')->insert([
'roleID' => $id
]);
//return $data;
return redirect(route('allRole'));
}
When i insert any role then it insert new data in roles table but i am not getting roleID in user_roles table.I get an error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(`amarjobs`.`user_roles`, CONSTRAINT `fkuserRolesuserID` FOREIGN KEY
(`userID`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE
CASCADE) (SQL: insert into `user_roles` (`roleID`) values (14))
Where is the problem i have done? Thanks in advanced.
Searched result:
1. First Solution.
2. Second Solution.
As you can see your user_roles table required userID column & you aren't passing the field while inserting that's what generating the error.
DB::table('user_roles')->insert([
'roleID' => $id,
'userID' => $userId, //pass your userID here
]);
Also I like to mention couple of things you are naming your DB table column names in camel case which is bad you should be using underscores & as db sqls are generally case insensitive so using userID is equivalent to userid.
Also you are using DB::insert it will not insert any created_at or updated_at field or other eloquent features so I suggest you insert using eloquent model & using relations which is the beauty of laravel & eloquent active records
try like this
public function store(Request $request)
{
//
$role = [];
$role['role'] = $request->input('role');
$data= Role::create($role);
$userdata = User::all();
$user_id = $userdata->first()->id;
$id= $data->id;
DB::table('permissions')->insert([
'role_id' => $id
]);
DB::table('user_roles')->insert([
'roleID' => $id,
'userID' => $user_id
]);
//return $data;
return redirect(route('allRole'));
}
Here $userdata = User::all(); you are selecting all user do you want all your to have this role then you have to loop through on it & insert it. Or if you want first user to have this role then it's fine.
Also I suggest I think you should read more Laravels documentation to clear things.
It seems you are trying to insert only roleID to user_roles table.
But within in your given error it seems the user_roles TABLE has also userID field what is foreign key and connect with users (id) table.
As user_roles is a pivot table and it has both roleID and userID and both are foreign key. So while inserting with only roleID value it's trying to insert the userID with the NULL value what is not matched with user Table any of IDs that's why Integrity constraint Violated.
So inserting data in a right way would be, you have to provide VALID userID as well.
$id= $data->id;
DB::table('user_roles')->insert([
'roleID' => $id,
'userID' => $EXISTING_USER_ID
]);
I think, it will solve your problem.
in your above error, you are missing the userID field, which is must in relationship perspective. so you should pass the userID then your code will be working.
$role = [];
$role['role'] = $request->input('role');
$data= Role::create($role);
$id= $data->id;
DB::table('user_roles')->insert([
'roleID' => $id,
'userID'=>1, // pass userID with whom you wan to attach new roleID
]);
return redirect(route('allRole'));
here is advance version of using relationship method
Add these method in respective models
user model
public function userRoles(){
return $this->belongsToMany('App\Role','user_roles','userID','roleID');
}
role model
public function roleUsers(){
return $this->belongsToMany('App\User','user_roles','roleID', 'userID');
}
and do this for insertion of roles.
$user = App\User::find(1);
$user->roles()->attach($roleId);
$role = [];
$role['role'] = $request->input('role');
$data= Role::create($role);
$id= $data->id;
$user->userRoles()->attach(['
'roleID' => $id,
'userID'=>$user->id
']);
return redirect(route('allRole'));

Inserting a has many relationship tables at the same time in laravel

I am using PHP Laravel Framework.I have 1 to M relationship tables order and products.
ORDER TABLE - orderid <--autoincrement primary key - orderdate - Name
PRODUCTS TABLE - productid <--autoincrement primary key - orderid <--foreign key reference to order table - productName - price
My models are as below -->
Order Model :
class Order extends Eloquent
{
protected $table = 'order';
public function products()
{
return $this->hasMany('Products','orderid');
}
}
Products Model :
class Products extends Eloquent
{
protected $table = 'products';
}
I have a form where I am taking the order date,name of the customer and the products details that can be more than one products.User can have one or many products in one order.So now i have to insert details about both the tables in one go .
I read this doc http://laravel.com/docs/eloquent#inserting-related-models they have given this below code for inserting related models -->
$comments = array(
new Comment(array('message' => 'A new comment.')),
new Comment(array('message' => 'Another comment.')),
new Comment(array('message' => 'The latest comment.'))
);
$post = Post::find(1);
$post->comments()->saveMany($comments);
But here they know the id to find from the parent table but in my case I have to insert details in the Order table and then the details about the products in the Products table for the order which was inserted just before . Problem is how to find the newly inserted orderid ? I am using autoincrement for orderid field in the Order table.
Simply:
$order = new Order;
... // assign some properties
$order->save();
$products = [new Product(...), new Product(...)];
$order->products()->saveMany($products);
And set the protected $primaryKey on the models, like Zwacky already said.
Now, I doubt it's the relation you want. That means every product exists only in the context of a single order. I think this should be many to many, but that's your call.
if you create model by model you shouldn't have any problems. if you save() the model, its primary key id property will be set with the last inserted id automatically. here some idea:
$products = [];
foreach (['product A', 'product B'] as $name) {
$product = new Product;
$product->name = $name;
$product->price = 15;
$product->save();
// $product->id will be set after save()
array_push($products, $product);
}
$someOrder->products()->saveMany($products);

how to fetch record from model through foreign key in yii

I am new in yii framework. I have three different tables in yii framework.
First Table
First table is language(id, language_name) // id is primary key.
Second Table
Second Table is verse(id,topic_id, verse_text) // id is primary key, topic_id is foreign key.
Third Table
Third table is verse_translations(id, verse_id, language_id, translations_text)
// id is primary key, language_id is foreign key references with language table, // verse_id is foreign key references with verse table.
Now My Question is.
I want to get all verse_text with specific topic_id.
So how to fetch all records from model Verse through foreign key i.e. topic_id and these record should be sent to view by data provider function.
At this time i am using.
My Controller Method
public function actionVerset()
{
$topic_id = 1;
$result=Verse::model()->with('topic_verse', $topic_id)->findAll();
$dataProvider=new CArrayDataProvider($result, array(
'id'=>'Verse',
'pagination'=>array(
'pageSize'=>2,
),));
$this->render('myverse',array('dataProvider'=>$dataProvider));
}
but it is not giving my desired result.
My Verse Model Relation Method
public function relations()
{
return array(
'topic' => array(self::BELONGS_TO, 'Topic', 'topic_id'),
'verseTranslations' => array(self::HAS_MANY, 'VerseTranslations', 'verse_id'),
'verseLanguage' => array(self::HAS_MANY, 'VerseTranslations', 'language_id'),
'topic_verse' => array(self::BELONGS_TO, 'Verse', 'topic_id'),
);
}
Any help will be appreciated.
Thanks.
To get all Verse records with a specific topic_id, this should do the trick:
$records = Verse::model()->findAllByAttributes(array('topic_id' => $topic_id));
When you have declared the relation in your model you dont need to fetch the data from db using with simply use
$result=Verse::model()->findAll();
and then when you use this
$result->topic->field_name of topic table
This will give the result of that.

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