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

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

Related

How to return model with relationsip in laravel?

I have two model Product and Category.
The categories table have id, and name columns.
While the products table have id, name, and category_id [foreign_key to category].
Here is my below code (already have category with values of 1, "School Supply"):
$product = new Product;
$product->category_id = 1;
$product->name = "pencil";
$product->save();
return $product->with('category');
My question is why it returns an error below when I try to get the data with the relation model? Someone knows how to do it exactly?
[34;4mIlluminate\Database\Eloquent\Builder[39;24m {#4069}
You can lazy eager load the relations using load method instead of with.
with is used for eager loading.
$product->load('category');
return $product;

How to insert id from both tables into pivot table using laravel query builder

I have three tables in database
users
locations
location_user (columns: user_id, location_id)
I'm fetching records from locations table in multiple-drop-down field of user registration form. While filling form user has to select value from drop-down and then submit.
After submitting the form I want to insert data into users table. At the same time I also want to insert id from users table into user_id column of location_user and selected value of locations from drop-down of user registration form into location_id column of location_user table.
I know how to get this to work using eloquent but I as i mentioned in the question I want to know how to deal with this task using query builder of laravel.
Is there any reason to use a pivot table here? If you're going to tie a location to a user then just add a location_id field to the user table and have a one to many relation (location, user). I don't see any reasoning to use pivot table here unless you want a user to have multiple locations.
Anyway if you follow my advice it becomes easier. But with the current table structure, you need to setup relationships in the respective models. Then on form submit, create the user and attach the location to the user.
User model
public function locations()
{
return $this->belongsToMany('App\Location');
}
Location model
public function users()
{
return $this->belongsToMany('App\User');
}
Controller
$user = User::create($request->all());
$user->locations()->attach($request->location_id);
you must use this code:
$user = new user;
$user->title = $request->title; // your value
$user->username = $request->username // your value
$user->save();
$user->locations()->attach([1,2]); // or ->attach($location_id);
/// or $user->locations()->sync([1,2])
this is a example for your project when use ORM Eloquent and define relationship in models.
you can attention my example:
model Product
class Product extends Model
{
public function Categories()
{
return $this->belongsToMany('App\Category','product_category','category_id');
}
}
model Category
class Category extends Model
{
public function Products()
{
return $this->belongsToMany('App\Product','product_category','product_id');
}
}
when you want insert in your database you must write this code in your controller
$validated = $request->validated();
$user = Auth::user();
$product = new Product;
$product->title = $request->title;
$product->off_price = $request->off_price;
$product->price = $request->price;
$product->available = $request->available;
$product->user_id = $user->id;
$product->save();
$product->Categories()->attach($request->categories/* this is an array*/);
Here, this creates 3 separate queries using the query builder to get to what you want.
$user_id = DB::table('users')->insertGetId(
['something' => 'something']
);
$location_id = DB::table('locations')->insertGetId(
['something' => 'something']
);
DB::table('location_user')->insert(
['user_id' => $user_id, 'location_id' => $location_id]
);
But Laravel's ORM deals with this, so if you have your models mapped properly, you could do something like this:
$location = $user->locations()->create([
'something' => 'something.',
]);
See here: https://laravel.com/docs/5.4/eloquent-relationships

Adding data from a column to another table's column Laravel 5.2

So, I want to store some products to the product table. I managed that. But now I want to attach a user id to each product, so it can correspond to a different user.
As for now, I have tried this, but it doesn't seem to work:
public function store(){
$product = Request::all();
$product = Product::create($product);
$user = User::whereId(Request::input('user'))->first();
$product->users()->attach($user);
return redirect()->route('products');
}
The relationship between users and products is this: a user_id column in products table is foreign keyand references to the id on users table
You can use relation methods to save related objects as:
Assuming relation name in User model is products
public function store() {
$product_array = Request::all();
$product = Auth::user()->products()->create($product_array);
return redirect()->route('products');
}
Here the create method will automatically add the appropriate user_id value to the new Product model.

Laravel Eloquent with()-> returning null

I am trying to use Eloquent to get a specific product that has a brand_id column that maps to a brands table, the brand array is coming back empty.
Is there anything obvious here that needs to be changed?
$product = Product::with('images')->with('brand')->select($fields)->where('display', '=', 1)->find($id);
//Product model
class Product extends Eloquent {
...
public function brand()
{
return $this->belongsTo('Brand');
}
//Brand model
class Brand extends Eloquent {
...
public function products()
{
return $this->hasMany('Product');
}
You have this:
$product = Product::with('images', 'brand')
->select($fields)
->where('display', 1)
->find($id);
You are getting null for brand and it could be because you have some specific fields and most probably you didn't select the foreing_key from the products table that creates the relationship with Brand, so if your products table contains the foreign_key (probably brand_id) of brand table then you have to select that foreign_key from the products table too. So, just add that foreign_key/brand_id in the $fields variable. Without the relation builder key (FK) the Brand won't be loaded.

Laravel 4 how to add user id as a default value when inserting new records

I am building app for enterprise
their are three table:
1- users table (belong to company)
2- companies table (has many users)
3- branches table (belong to company)
when adding a branch I want to pass the company id in the model by default by adding the following code to the branches model
protected $attributes = array(
'company_id' => Auth::user()->company->id,
);
this will reduce the hassle of inserting company_id for each insert or update of a record
You can override the save method of your Model:
class YourModelClass extends Eloquent {
public function save(array $options = array())
{
if( ! $this->company_id)
{
$this->company_id = Auth::user()->company->id;
}
parent::save($options);
}
}
Not everytime you do:
$model = new YourModelClass;
$model->name = 'a name';
$mode->save();
It will also add the company_id to that model

Categories