update auto Create_at & Update_at columns at laravel 5.4 - php

here some simple code I have. Actually I was trying to insert some Tag to my database and no problem to that.but once insert my tag created_at & updated_at columns not update and just NULL
how can i update auto this fields?
I don't have any model
just migration
here my tag migration:
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('tag');
$table->timestamps();
});

Use Eloquent to auto update created_at and updated_at fields.
Model::create($data);
Model::update($data);
When you're using raw queries or query builder, you'll need to update these fields manually.
DB::table('table_name')
->insert(['tag' => 'some_tag', 'created_at' => Carbon::now()]);

Related

Laravel, MariaDB timestamp column without default and onupdate trigger

I have following migration:
Schema::create('auctions', function (Blueprint $table) {
$table->id();
$table->timestamp('expired_at');
$table->timestamp('sold_at')->nullable()->default(null);
// other fields
});
Which creates a table with this structure:
Every time I try to update sold_at field only, It changes the expire_at field also, which is so annoying and against my project's logic! How should I fix my migration to prevent this?
My update record code:
Auction::query()->where('id',1)->update([
'sold_at' => now()
]);
Change your column to a datetime column:
Schema::create('auctions', function (Blueprint $table) {
$table->id();
$table->dateTime('expired_at');
$table->timestamp('sold_at')->nullable()->default(null);
// other fields
});
https://laravel.com/docs/9.x/migrations#column-method-dateTime

(errno: 150 "Foreign key constraint is incorrectly formed") in many-to-many relationship in Laravel

I'm try to create many-to-many that link with customer and shop in laravel but stuck in this error (errno: 150 "Foreign key constraint is incorrectly formed") and still, not figure it out.
Here my customers table
Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('shop_id');
$table->string('name');
$table->string('email');
$table->string('phone');
$table->timestamps();
$table->foreign('shop_id')->references('id')->on('shop');
});
Here my shops table
Schema::create('shops', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('customer_id');
$table->string('name');
$table->timestamps();
$table->foreign('customer_id')->references('id')->on('customer');
});
My Shop Model
protected $fillable = ['name'];
public function customer()
{
return $this->belongsToMany(\App\Customer::class);
}
My Customer Model
protected $fillable = ['name', 'email', 'phone'];
public function shop()
{
return $this->belongsToMany(\App\Shop::class);
}
Any Help? Thanks in advances....
Check your Schema -
Its should be shops not shop...
$table->foreign('shop_id')->references('id')->on('shops');
and similarly customers not customer...
$table->foreign('customer_id')->references('id')->on('customers');
Note for you. Don't use foreign command in table create command together.
Make sure always new migration file for adding foreign key's inside table.
Cause sometime its generate Errors while migrating ..
open your bash shell or PHP Storm Terminal or CMD
php artisan make:migration foreign_customer_id_at_table_shops --table=shops //you Can use your own migration name what you want
at foreign_customer_id_at_table_shops migration file
UP
$table->foreign('customer_id')->references('id')->on('customers');
DOWN
$table->dropForeign(['customer_id']);
Put the foreign key in relationship rather than in migration.
public function customer()
{
return $this->belongsToMany('\App\Customer::class','id','shop_id');
}
public function shop()
{
return $this->belongsToMany('\App\Shop::class','id','customer_id');
}
The relation of many-to-many need third table pivot table which you miss it.
for do that create new migration.
php artisan make:migration create_customer_shop
there is no need create model for pivot table
then you Schema pivot table something like this.
Pivot table
Schema::create('cutomer_shop', function (Blueprint $table) {
$table->increments('id');
$table->integer('customer_id')->unsigned();
$table->integer('shop_id')->unsigned();
$table->timestamps();
$table->foreign('customer_id')->references('id')->on('customers');
$table->foreign('shop_id')->references('id')->on('shops');
});
The two table shops and customers doesn't have any direct relations they have relation by just pivot table.
Note: make sure all three table id type increments('id') and all foreign key are $table->integer('shop_id')->unsigned(); otherwise give you incorrect format error.

Increase the value of count in laravel 5.6

I have two tables rta_list and rta_reg_company. I have a column count in rta_list table.
Schema::create('rta_list', function (Blueprint $table) {
$table->increments('rta_id');
$table->string('rta_name');
$table->string('rta_address');
$table->string('rta_phone');
$table->string('rta_email')->unique();
$table->integer('count');
$table->timestamps();
});
Schema::create('rta_reg_company', function (Blueprint $table) {
$table->increments('company_id');
$table->integer('rta_id')->unsigned();
$table->foreign('rta_id')
->references('id')
->on('rta_lists')
->onDelete('cascade');
$table->string('company_name');
$table->string('company_isin');
$table->string('company_script');
$table->string('company_address');
$table->string('company_phone');
$table->string('company_email');
$table->timestamps();
});
I want to increase the value of count of rta_list table by rta_id when I add new RTA Registered Company. For eg: if i add one company then, The value must be added in rta_reg_company table and count must be 1 in count column in rta_list table.
Also also how to show the count value by rta_id in view..
Help Needed.....
you can use laravel Observer to raise an event on a model creation.then you can update as below on model Observer:
public function created(Company $company)
{
DB::table('rta_list')->increment('count');
}

Optimize Laravel Eloquent whereHas() query - very slow

I am using Laravel 5.4
I have 3 models: Order, OrderLine and Product.
Order hasMany() OrderLines
OrderLine hasOne() Product via the product_id in the OrderLine model (I have properly indexed this, at least I think!)
My requirement is to retrieve all Orders and OrderLines where the Product is for a certain brand name.
Here is my eloquent query. I know the query works but it seems to infinitely run when put on a large dataset (circa 10,000 Orders, 12,000 OrderLines/Products)
$orders = Order::whereBetween('order_date', [$this->start_date,$this->end_date])
->whereHas('lines', function ($q1){
$q1->whereHas('product', function ($q2){
$q2->where('brand', 'Brands>SanDisk');
});
})->with('lines')->with('lines.product')->get()->toArray();
This produces the following SQL when debugging via toSql() method.
select
*
from `orders`
where
`order_date` between ? and ?
and
exists (select * from `order_lines` where `orders`.`id` =`order_lines`.`order_id`
and
exists (select * from `products` where `order_lines`.`product_id` = `products`.`id` and `brand` = ?))
My 3 migrations to create the tables are as follows (I have removed anything except keys for simplicity):
Schema::create('orders', function (Blueprint $table) {
$table->increments('id');
});
Schema::create('order_lines', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id');
$table->integer('order_id');
});
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
});
I then added the following index:
Schema::table('order_lines', function (Blueprint $table) {
$table->integer('product_id')->unsigned()->change();
$table->foreign('product_id')->references('id')->on('products');
});
Results of EXPLAIN syntax as follows:
1 PRIMARY orders ALL 91886 Using where
2 DEPENDENT SUBQUERY order_lines ALL 93166 Using where
3 DEPENDENT SUBQUERY products eq_ref PRIMARY PRIMARY 4 mymemory_main.order_lines.product_id 1 Using where
Try this:
mpyw/eloquent-has-by-non-dependent-subquery: Convert has() and whereHas() constraints to non-dependent subqueries.
mpyw/eloquent-has-by-join: Convert has() and whereHas() constraints to join() ones for single-result relations.
$orders = Order::query()
->whereBetween('order_date', [$this->start_date, $this->end_date])
->hasByNonDependentSubquery('lines.product', null, function ($q) {
$q->where('brand', 'Brands>SanDisk');
})
->with('lines.product')
->get()
->toArray();
That's all. Happy Eloquent Life!

Laravel - A show can have multiple providers

So I am trying to figure a solution to this but not sure exactly how to do this. I have a table that stores all the shows that happen. In a given show I can have multiple providers attend that show. A provider could also attend many shows as well. So how do I store this in the DB and do the eloquent relationship?
Show Schema
Schema::create('shows', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('number')->unsigned();
$table->dateTime('airDate');
$table->string('podcastUrl')->nullable();
$table->timestamps();
});
Provider Schema
Schema::create('providers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('shortName')->nullable();
$table->string('image')->nullable();
$table->string('social')->nullable();
$table->timestamps();
});
Would I store the provider_id in the shows schema?
Update 1
So I created a new migration for a pivot table
Schema::create('provider_show', function (Blueprint $table) {
$table->integer('provider_id')->unsigned()->index();
$table->foreign('provider_id')->references('id')->on('providers')->onDelete('cascade');
$table->integer('show_id')->unsigned()->index();
$table->foreign('show_id')->references('id')->on('shows')->onDelete('cascade');
$table->primary(['provider_id', 'show_id']);
});
Then in the show model I created the following
public function providers()
{
return $this->belongsToMany(Provider::class);
}
Now when I am saving a new show I added a multiselect to select the providers I want
$show = new Show;
$show->name = $request->name;
$show->number = $request->number;
$show->airDate = $request->airDate;
$show->podcastUrl = $request->podcastUrl;
$show->providers()->attach($request->providerList);
$show->save();
Session::flash('message', "Created Successfully!");
return back();
Then when I save I get the following error
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: provider_show.show_id (SQL: insert into "provider_show" ("provider_id", "show_id") select 1 as "provider_id", as "show_id" union all select 2 as "provider_id", as "show_id")
Create a provider_show migration which will act as your pivot table.
This table would contain both provider_id and show_id which will provide the many-to-many relationship between those entities.
Then on your Provider model you can provide a shows() method which returns a BelongsToMany relationship.
// In your Provider model
public function shows()
{
return $this->belongsToMany('App\Show');
}
Note that Laravel by default looks for a pivot table name based alphabetically on the two relationships.
You can also add the inverse on your Show model by providing a providers() method that also returns a BelongsToMany relationship.

Categories