I am trying to store name of ordered meals for each user in order table, I am using Larvel - laravel-5

this is the order table
$table->string('first_name');
$table->string('last_name');
$table->string('phone_number');
$table->string('meal_name');
$table->Integer('quantity');
and this is the meal_user table which contains the order informations before confirming it by the user
$table->double('quantity');
$table->text('note')->nullble();
$table->string('meal_size');
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->string('phone_number')->nullable();
$table->bigInteger('location_id');
$table->bigInteger('user_id')->nullable();
$table->bigInteger('meal_id');
what I am trying to do is when the user confirm his orders it stores in the order table, but for each user has one record with all ordered meal names

Related

Why I can't do a migration with constraint foreign key

for a homework i have to do a todolist in laravel 7 i do my db but when i try to create a foreign key to the table task
and a table categories
the program fail with the formula :"SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'categories' (SQL: alter table tasks add constraint tasks_category_id_foreign foreign key (categ
ory_id) references categories (id) on delete cascade)"
i've done it a lot of time but i don't understand why i doesn't work if someone could explains
the right way to do it
The migration is trying to create the tasks table before categories, the categories table still doesn't exist at the time it tries to create the FK.
Swap the order of your migrations changing its filename. Each migration file at database/migrations has a date-time before the name. Alter it so the tasks migration has a date greater than the categories one.
will Gus Costa is right and you should do as he says but i want to add that your
foreign key should be unsigned
and here you will find some good answers
"General error: 1005 Can't create table" Using Laravel Schema Build and Foreign Keys
// CREATING TABLE
Schema::create('table_name', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->integer('field_id')->unsigned; //for field that contains foreign key constraint
});
// FOREIGN KEY CONSTRAINT
Schema::table('stock', function ($table) {
$table->foreign('field_id')->references('id')->on('some_table')->onDelete('cascade')->onUpdate('cascade');
});

Laravel auto-increment on non-primary field

There is my migration. I want id field being auto-incremented but not primary. Is it possible? This migration throws an exception Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key
Schema::create('tests', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('project_id');
$table->unsignedInteger('model_id');
$table->timestamps();
$table->dropPrimary('id');
$table->foreign('project_id')
->references('id')
->on('projects')
->onDelete('cascade');
$table->primary(['project_id', 'model_id']);
});
This is not Laravel error. you can't have two auto increment column in mysql table. (of course if you are using mysql) but I think none of any relational database gives you ability to have two auto increment columns.
But there is another way to do that.
look at this question
This is not a Laravel error but a MySQL error. As the error message says: it must be defined as a key. You are dropping the primaryKey constraint on the id column. You should try setting it as an index.
try the following $table->unsignedInteger('id')->index()->autoIncrement();. This will make it an AI integer and also an index but not a PK.

foreign key constraint: cannot drop table because other objects depend on it

I'm running migrations on Laravel 5.1 and am switching DBs from Mysql to Postgres.
Typically I could set foreign key checks to 0 prior to running down migrations as such:
- DB::statement('SET FOREIGN_KEY_CHECKS = 0');
- Do stuff
- DB::statement('SET FOREIGN_KEY_CHECKS = 1');
Postgres does not offer this.
In running down migrations, I get error:
Dependent objects still exist: 7 ERROR: cannot drop table table2 because other objects depend on it
DETAIL: constraint table1_table2_table1_id_foreign on table table1_table2 depends on table table2
HINT: Use DROP ... CASCADE to drop the dependent objects too. (SQL: drop table "table2")
Question: This complaint is curious to me as I set ->onDelete('cascade'); on the foreign key creations. Why is this happening?
Snippets:
Create Table1 Table:
...
public function down()
{
Schema::drop('table1_table2');
Schema::drop('table1');
}
Create Table2 Table (Called after table 1 migration):
...
public function down()
{
Schema::drop('table2');
}
Create Foreign Keys Table (last migration to be called)
public function up()
{
Schema::table('table1_table2', function(Blueprint $table)
{
$table->foreign('table1_id')->references('id')->on('table1')->onDelete('cascade');
$table->foreign('table2_id')->references('id')->on('table2')->onDelete('cascade');
});
...
}
public function down()
{
...
Schema::table('table1_table2', function(Blueprint $table)
{
$table->dropForeign('table1_id');
$table->dropForeign('table2_id');
});
...
}
This complaint is curious to me as I set ->onDelete('cascade'); on the foreign key creations. Why is this happening?
The key term here is "on delete" - when you delete a row from one table, that option will determine whether rows with foreign keys referencing that row will be deleted as well.
However, your change script is not deleting rows, it is dropping the table. This is therefore a different event, not effected by the ON DELETE option on the foreign key.
The CASCADE mentioned in the hint is a keyword on the DROP TABLE statement, discussed in the manual under "Dependency Tracking":
Key quotes:
When you create complex database structures involving many tables with foreign key constraints, views, triggers, functions, etc. you implicitly create a net of dependencies between the objects. For instance, a table with a foreign key constraint depends on the table it references.
and:
if you do not want to bother deleting all the dependent objects individually, you can run DROP TABLE products CASCADE; and all the dependent objects will be removed, as will any objects that depend on them, recursively. In this case, it doesn't remove the orders table, it only removes the foreign key constraint.
and:
Almost all DROP commands in PostgreSQL support specifying CASCADE.
For my case; you can get this error with this scenario;
If your table seems rollbacked in migration table (ex: maybe forget drop function first time) but table still exists on database you can get this error. migrate:fresh command will fail with given error message for this scenario.
You can drop table manually or add a row to migration table with that migration name and everything will be working normally.

3 Tables Relations by Using Eloquent

I have some relations on my db and I'm very confused how I can do this with eloquent. I have three tables that I want to connect eachother.
Users table - Contains users and these users have 3 roles (customers, managers, employee etc.) And users with manager role have more than one customers or employes.
Comps table - Contains company infos, (customers company, manager company, employee company etc.) employes can have same company.
Images table- this table contains user profile images, comp logo images etc.
I want to take a user's customers informations with images. I made the following relation between comp table and user table in User model. But I can't take comp image with this relation.
public function customers() {
return $this->belongsToMany('App\Comp', 'user_customers', 'user_id', 'comp_id');
}
user_customers table is a relation table which shows which user is a customer of which user.
user_customers table:
id,
user_id,
customer_user_id,
comp_id,
How can I get comp's logo image?

Soft delete on a intermediate table for many-to-many relationship

How do I set soft delete on an intermediate table which is connecting two different types of entities? I've added deleted_at column, but the docs say that I need to put this into the model:
protected $softDelete = true;
Of course, I don't have a model for an intermediate table.
Any idea?
You can put a constraint on the Eager Load:
public function groups()
{
return $this
->belongsToMany('Group')
->whereNull('group_user.deleted_at') // Table `group_user` has column `deleted_at`
->withTimestamps(); // Table `group_user` has columns: `created_at`, `updated_at`
}
Instead of HARD deleting the relationship using:
User::find(1)->groups()->detach();
You should use something like this to SOFT delete instead:
DB::table('group_user')
->where('user_id', $user_id)
->where('group_id', $group_id)
->update(array('deleted_at' => DB::raw('NOW()')));
You could also use Laravel's Eloquent BelongsToMany method updateExistingPivot.
$model->relation->updateExistingPivot($relatedId, ['deleted_at' => Carbon\Carbon::now()]);
So to use #RonaldHulshof examples you have a User model with a groups relationship which is a belongsToMany relationship.
public function groups() {
return $this->belongsToMany(Group::class)->whereNull('groups_users.deleted_at')->withTimestamps();
}
Then in order to soft delete the pivot table entry you would do the following.
$user->groups()->updateExistingPivot($groupId, ['deleted_at' => Carbon\Carbon::now()]);
As far as I understand it; an intermediate table is simply a length of string attaching one tables record to a record in another table and as such it does not require a soft delete method.
To explain, imagine you have a Users table and a Groups table, each user can have more than one Group and each Group can belong to more than one User. Your pivot table may be User_Group or something like that and it simply contains two columns user_id and group_id.
Your User table and Group table should have a deleted_at column for soft deletes, so when you "delete" say a Group, that group association will not appear in $User->Groups() while the pivot table row has remained unaffected. If you then restore that deleted Group, it will once again appear in $User->Groups().
The pivot table row should only be affected if that group record is hard deleted, in which case the pivot rows should also be hard deleted.
Now I have explained why I do not believe you need to add soft delete to a pivot table; is there still a reason why you need this behavior?

Resources