Update many multiple data with tables hasmany and belongsTo? - laravel-4

sorry for my english
I want two tables
Invoices
id
user_id
name
created_at
update_at
Invoicesitems
id
invoice_id
title
createad_at
update_at
Models
class Invoices extends eloquent{
public function invoicesitems(){
return $this->hasMany('Invoicesitem');
}
}
class Invoicesitems extends eloquent{
public function invoices(){
return $this->belongsTo('Invoice');
}
}
Now, for update the items of my invoices?
Example my invoices have 5 item, i need update to 10 items
first delete all items of my invoices and insert new ???
$invoices = Invoices::findOrFail($id);
$dataupdate = array(
'user_id' => Input::get('user'),
'name' => Input::get('name'),
);
$invoices->fill($dataupdate);
$invoices->save();
//Ok update invoices, now how to update items?
Thanks you.

If your business logic allows - you can just replace the invoice items.
$invoice = Invoices::findOrFail($id);
$dataupdate = array(
'user_id' => Input::get('user'),
'name' => Input::get('name'),
);
$invoice->update($dataupdate);
// replace invoice items
$invoice->invoicesitems()->delete();
$invoice->invoicesitems()->create($invoiceItems);
Note! This is quite straight solution. You can improve by using insert() method instead of create() for batch insert.

Related

How to create data into junction table many to many relationship without create data into the junction point to

It inserts both table inside tags and tagables, what i want is just to insert into tagables ( junction ) table. Cause before it insert into tagables, theres code to check first if tag will insert into tags table already exist or not, if exist just grab the id. To make it simple to my problem. i just don't include code to check if tags is exist or not.
post model
public function tags(){ return $this->morphToMany( Tag::class, 'tagable', 'tagables', null, 'tag_id ); }
post controller
// tags table theres a row id 1 with name greeting
$post = Post::create( ['body' => 'Hello World'] );
$post->tags()->create( ['tag_id' => 1] );
Tables
// posts table
$table->mediumIncrements('post_id');
$table->string('body');
// tags table
$table->mediumIncrements('tag_id');
$table->string('tag_name');
//tagables table
$table->unsignedMediumInteger('tag_id');
$table->unsignedMediumInteger('tagable_id');
$table->string('tagable_type');
I think the simplest way do this to start by creating the tag with the eloquent method 'firstOrCreate', and then when you already have a new tag or existing tag you can add this tag to a new Post. The code may look like something like this:
class Tag extends Model
{
protected $guarded = [];
public function posts()
{
return $this->morphedByMany(Post::class, 'taggable');
}
}
$tag = Tag::firstOrCreate(
['tag_name' => 'traveling'],
);
$post = $tag->posts()->create([
'body' => 'My new interesting post',
]);

How to get hasMany relation in laravel?

Pls bear with me . I am working on api with laravel :
The Idea is that I have table called ( cards ) this table contain column called ( service_id ) .
this column has relation with table ( services ).
This is cards database structure in image :
image of database
All thing is good with add one service_id , but now I need to make table cards hasMany services
So How can I do it , and the database structure what will be?
this is my old code to add new card :
public function store(Request $request)
{
$validator = \Validator::make($request->all(), [
'user_id' => 'required|unique:cards|exists:users,id',
'service_id' => 'required',
'numPhone' => 'required',
'location' => 'required',
],[],[
'user_id' => '( User id )',
'service_id' => 'service id',
'numPhone' => 'Phone Number',
]);
if ($validator->fails()){
return $this->apiRespone(null,$validator->errors()->all(),'Some input required');
}
$card = Card::create($request->all());
return $this->apiRespone(new cardResource($card),'Add card Successfully',201);
}
I think you need to create pivot table "cards_services" that has column id, card_id, service_id column and used relationship Sync() method of laravel to store/update.
In cards modal
public function services(){
return $this->belongsToMany('App\Models\Service','cards_services', 'card_id', 'service_id');
}
For save it.
$cards->services()->sync([1,2]); //1 and 2 is service ID and $cards is card modal object
here you have service_id in your cards table
so i think it will be easier to implement service hasMany cards and cards belongsTo service
add this in your service model
public function cards(){return $this->hasMany('App\Cards');}
add this in your cards model
public function service(){return $this->belongsTo('App\Service');}
Note: please rewrite path and Model name according to your requirement

Add data to a Laravel pivot table

I have a database with 3 tables : users, events and user_event.
I create my event. Once my event is created, I would like to add users.
How can I add him via a form to add users?
My pivot table contain :
event_id, user_id
Do I need to create a UserEventController?
My model relations :
public function users()
{
return $this->belongsToMany('User')->withPivot('user_event');
}
For create an event :
public function store(Request $request)
{
$this->validate($request, [
'course_name' => 'required|max:255',
'academic_year' => 'required|max:4|min:4',
'exam_session' => 'required',
'date_event' => 'required'
]);
$event = new Event();
$event->course_name = $request->course_name;
$event->academic_year = $request->academic_year;
$event->exam_session = $request->exam_session;
$event->date_event = $request->date_event;
$event->save();
}
Thanks for your help !
So you need to use the attach()method :
$event->users()->attach($userId);
more informations here : Laravel Eloquent - Attach vs Sync
Since the event is already created, you can just use the event object to add an existing user, create a new one, or maybe even sync a list of users.
//create a new user
$event->users()->create(['name' => 'user name', 'email' => 'user email']);
//attach existing user
$event->users()->attach($userId);
//sync multiple existing users passing array of user ids
$event->users()->sync([1,2,4]);
You can see details about all of those methods and a few more here: https://laravel.com/docs/5.7/eloquent-relationships#inserting-and-updating-related-models

how to save multiple dropdownlist yii2

I'm trying to save multiple data from a dropdownlist, I have 2 tables Asistencia and Mecanico in the table Asistencia i have this in the _form
<?php
echo $form->field($model, 'mecanico_id[]')
->dropDownList(ArrayHelper::map(Mecanico::find()->all(), 'id_mecanico', 'nombre'),
[
'multiple'=>'multiple',
'class'=>'chosen-select input-md required',
]
)->label("Mecanicos");
?>
i know if i want to save multiple data i have to change in controllers-> actionCreate/Update but i dont know how. Here is my actionCreate
public function actionCreate()
{
$model = new Asistencia();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id_asistencia]);
}
return $this->render('create', [
'model' => $model,
]);
}
I need sample controller code explaining how to save multiple items from a drop down list to the database, as well as update the list of saved items. Thanks.
here is my table of Asistencia
Asistencia table
Table of Mecanico
Mecanico table
and the relation of those 2 table
enter image description here
For example you have Product and Category many to many relation.
In your Product model,
Declare field:
public $categories_ids;
Put it in 'safe' in rules():
[['categories_ids'], 'safe']
3.Declare AfterSave function:
public function afterSave($insert, $changedAttributes) {
// If this is not a new record, unlink all records related through relationship 'categories'
if(!$this->isNewRecord) {
// We unlink all related records from the 'categories' relationship.
$this->unlinkAll('categories', true);
// NOTE: because this is a many to many relationship, we send 'true' as second parameter
// so the records in the pivot table are deleted. However on a one to many relationship
// if we send true, this method will delete the records on the related table. Because of this,
// send false on one to many relationships if you don't want the related records deleted.
}
foreach($this->categories_ids as $category_id) {
// Find and link every model from the array of ids we got from the user.
$category = Category::findOne($category_id);
$this->link('categories', $category);
}
parent::afterSave($insert, $changedAttributes);
}
Decare AfterFind function():
public function afterFind(){
parent::afterFind();
$this->categories_ids = ArrayHelper::getColumn($this->categories, 'id');
}
Declare relation:
public function getCategories() {
return $this->hasMany(Category::className(), ['id' => 'category_id'])->viaTable('product_category', ['product_id' => 'id']);
}
I hope it will help to you.

How to create Eloquent model with relationship?

How to create Eloquent model with relationship?
I have:
Person table
id
firstname
lastname
Employee table
id
person_id
position
I want to do something like this:
Employee::create([
'firstname' => 'Jack',
'lastname' => 'London',
'position' => 'writer'
])
I know, that can create two model and then associate their. But may be there is a way do this more beautiful?
First, you have to create relation in your Person model
class Person extends Model
{
protected $fillable = ['firstname', 'lastname'];
public function employee()
{
return $this->hasOne('App\Employee');
}
}
After that in your controller you can do:
$person = Person::create($personData);
$person->employee()->create($employeeData);
As #Alexey Mezenin mentioned you can use:
$person = Person::create(request()->all());
$person->employee()->create(request()->all());
Also inverse would be:
class Employee extends Model
{
protected $fillable = ['position'];
public function person()
{
return $this->belongsTo('App\Person');
}
}
You still need to create person first, so if you're looking for readable and consize solution, you can do is this:
$data = [
'firstname' => 'Jack',
'lastname' => 'London',
'position' => 'writer'
];
$person = Person::create($data);
$person->employee()->create($data);
I'd suggest you create a static method that creates the instance and related models. Many times you not only create a model, but you may have to populate it with some additional data and having a single createModel() method is a best practice.
In my case:
public static function createCompany($data) : Company {
$company = new Company($data);
$company->save();
$company->settings()->create();
// TODO Configure settings according to $data
$company->blog()->create();
// TODO: Create demo blog post
// TODO: Create default admin user.
// TODO: Etc.
}
All these details can be abstracted from the controller, in which I only call:
$company = Company::createCompany($request->all());

Resources