Unable to insert into PostgreSQL using laravel eloquent ORM - php

I did my research a lot before posting this.
I am getting the following error when trying to insert a record into PostgreSQL using Laravel eloquent ORM.
This is the error:
Illuminate \ Database \ QueryException
SQLSTATE[42703]: Undefined column:
7 ERROR: column "id" does not exist LINE 1: ...ed_at", "created_at")
values ($1, $2, $3, $4)
returning "id" ^ (SQL: insert into "fb_post_like_counts" ("post_id", "count", "updated_at", "created_at") values (293843523498_10152007721598499, 0, 2014-03-12 16:56:24, 2014-03-12 16:56:24) returning "id")
This is the database table create schema:
Schema::create('fb_post_shares_counts', function($table)
{
//
$table->string('post_id');
$table->string('count')->default(0);
// created_at updated_at deleted_at
$table->timestamps();
$table->softDeletes();
// set composite keys
$table->primary(array('post_id', 'updated_at'));
});
and this is the code i am trying to execute:
// SAVE POST SHARES
$post_share_count = new FbPostShareCount;
$post_share_count->post_id = $response['id'];
$post_share_count->count = $fql_post['share_count'];
$post_share_count->save();
and I created a model class FbPostShareCount extends Eloquent.
I know that laravel does not support complex keys but this problem did not occur when I was using MySQL

Set the primary key in your FbPostShareCount model as
class FbPostShareCount extends Eloquent {
protected $primaryKey = 'post_id';
...
}

Laravel eloquent ORM have auto increment, So set up primaryKey = null and increment = false.
protected $primaryKey = null;
public $incrementing = false;

have you tried using the correct data type for post id?
$table->integer('post_id');

Related

laravel orm update document [duplicate]

This question already has answers here:
Laravel Unknown Column 'updated_at'
(6 answers)
Closed 2 years ago.
I have been trying to update a document using laravel ORM but getting exception stating a unknown column updated_at.
This column is not in database table, and neither have I mentioned in the query.
$foo = ProductMatchUnmatchHistory::where('product_match_unmatches_id', $pmu->id)
->update(['is_latest'=>0]);
ProductMatchUnmatchHistory model:
protected $fillable = [
'product_match_unmatches_id',
'human_verdict',
'ai_result',
'updated_on',
'updated_by',
'is_latest'
];
The table has the same columns as in $fillable array, with additional id primary key.
Here's the exception message:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list' (SQL: update `product_match_unmatch_histories` set `is_latest` = 0, `updated_at` = 2019-11-20 12:20:02 where `product_match_unmatches_id` = 1759)
I have no clue from where the updated_at column is added to the query.
If you don't want to use the updated_at and created_at fields from Laravel's Eloquent models, edit your ProductMatchUnmatchHistory.php model and set $timestamps = false.
class ProductMatchUnmatchHistory extends Model
{
//....
$timestamps = false;
//....
}
Additional Info
Laravel Models automatically set a created_at field when an entry is created and update the updated_at column when you do any changes to a row. This is handled through the $timestamps field on the model. If set to true, which is default, laravel will assume that your models have created_at and updated_at fields.
In most cases this is pretty helpful. You can easily add these fields in your migration by just adding $table->timestamps();.
See https://laravel.com/docs/5.8/eloquent#eloquent-model-conventions
(under Timestamps)
please change
you must define table name
protected $table = 'your table name';
protected $fillable = [
'product_match_unmatches_id',
'human_verdict',
'ai_result',
'updated_on',
'updated_by',
'is_latest'
];
$timestamps = false;
First please check in your table updated_at exist? because sql error say column not found
#Azima you should added the column in your table otherwise you will get this error, because eloquent updating that column and its not present in table or you can $timestamps=false in your Model

how I can add 2 auto-increment columns in the same table in the laravel database

I want to know if I can add 2 auto-increment columns in the same table in laravel? but the second has different value to start with it?
uniID I want to start from 43600000,
Schema::create('students', function (Blueprint $table){
$table->increments('id');
$table->increments('uniID');
$table->integer('student_id');
$table->timestamps();});
DB::statement("ALTER TABLE students AUTO_INCREMENT = 43600000;");
Laravel doesn't support this because databases don't generally support it. The increments() and bigIncrements() column types cannot be used multiple times in the same table Schema and will fail on create:
PDOException: SQLSTATE[HY000]: General error: 1 table "students" has more than one primary key
But if uniId will always be 43600000 larger than id, you can use a computed attribute in Eloquent:
class Student
{
public function getUniIdAttribute()
{
return $this->id + 43600000;
}
}
Then you can use this in your controllers or Blade templates:
>>> $user = Student::first()
=> App\Student{#3078
id: 1,
...
}
>>> $student->uniId
=> 43600001
The downside to this approach is that you won't be able to use uniId as a foreign key in other tables.

How associate model server with stats in Laravel

I have two models:
Model Server with columns ip, port, players_online, votes.
And I have model Stats with columns: server_id, online, votes.
In stats model I have:
protected $fillable = ['server_id', 'votes', 'online'];
public function server() {
return $this->belongsTo('App\Models\Server');
}
I have code:
$servers = Server::all();
foreach($servers as $server) {
$statss = getMcServer($server->ip, $server->port);
$server->players_online = $statss['online'] ? $statss['online'] : 0;
$stats = new Stats();
$stats->server()->associate($server);
$stats->save();
$server->save();
}
When I use associate, I get error:
SQLSTATE[HY000]: General error: 1364 Field 'online' doesn't have a default value (SQL: insert into `stats` (`server_id`, `updated_at`, `created_at`) values (24, 2018-05-15 12:12:21, 2018-05-15 12:12:21))
Normally this should work:
$servers = Server::all();
foreach($servers as $server) {
$statss = getMcServer($server->ip, $server->port);
$server->players_online = $statss['online'] ? $statss['online'] : 0;
$stats = new Stats();
$stats->online = $server->players_online;
$stats->votes = $server->votes;
$stats->server()->associate($server);
$stats->save();
$server->save();
}
Looking at your error looks like the field online from stats model is set as guarded or not set as fillable, you should add it in the fillable array of the model, so you can set the data and then save it to the database:
protected $fillable = ['votes','online'];
You can read more about fillable and guarded in the Eloquent -> Inserting & Updating Models from Laravel official docs.
In case your fillable array is fine, probably the columns of your database are not nullable or doesn't have a default value, if this data is not mandatory or is optional, change them to nullabe or add a default value and the problem is going to be solved.

Updating records in model

I try update model in database.
I have request with naw values and value.
'old_log'- old value to find row in database.
public function UserChange2(Request $request){
dump($request);
$data=$request->all();
$log = $request->input('old_log');
dump($log);
$user=userModel::select(['fam','im','ot','phone','log','pass'])->where('log',$log)->first();
$temp=$request->input('fam');
$user->fam=$temp;
$temp=$request->input('im');
$user->im=$temp;
$temp=$request->input('ot');
$user->ot=$temp;
$temp=$request->input('phone');
$user->phone=$temp;
$temp=$request->input('log2');
$user->log=$temp;
$temp=$request->input('pass');
$user->pass=$temp;
dump($user);
$user->save;
}
But the records in the table are not updated.
Model:
class userModel extends Model
{
public $timestamps = false;
protected $fillable=['fam','im','ot','phone','log','pass','reg','token','date','position'];
}
Now:
dump($request);
$data=$request->all();
$log = $request->input('old_log');
dump($log);
$user=userModel::select(['fam','im','ot','phone','log','pass'])->where('log',$log)->first();
$user->fill($request->all())->save();
$user->save;
And error:
Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update user_models set fam = y, phone = gggg, pass = tttyyyyyyyy where id is null)
Your userModel extends Model, which is an Eloquent Model and by default expects that the related table has a primary key called id.
The error
Column not found: 1054 Unknown column 'id' in 'where clause'
indicates that the column id does not exist.
Check your table definition. Is this a table in a DB that was created outside your Laravel project?
If not, check your database migration whether the primary key id is defined. Read here about database migrations.
If there is already a primary key that you want to use instead of id, you can tell Eloquent:
protected $primaryKey = 'your_primary_key';
See here.
You likely don't have fillables completed in your Model.
Go to the model which should be blank and add the fields that can be completed:
example:
protected $fillable = [
'phone', 'log2', 'pass',
];
You can find this in the Laravel manual here:
https://laravel.com/docs/5.5/eloquent#mass-assignment
remove select from your eloquent. try this..
$user=userModel::where('log',$log)->first();
$user::create($request->all());
edit
$user=userModel::where('log',$log)->first();
$request->request->add(['log' => $request->log2]);
$user::create($request->all());

Laravel Eloquent still throwing error with updated_at column even I ignored it

I am developing a website using Laravel 5.2. I am working with database. So I used Laravel eloquent model to make the code neat and clean. But one of my Eloquent is throwing unknown updated_at column exception even if I already ignored it.
I ignored or override the built in function like this in my Entity.
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
//
protected $fillable = ['name', 'mm_name'];
public function setUpdatedAt($value)
{
// Do nothing.
}
public function setCreatedAt($value)
{
// Do nothing.
}
}
I deleted updated_at column from categories table. So if I update the category, updated_at column should be ignored.
So updated like this
function updateCategory($bag)
{
$category = Category::find($bag->id);
if($category)
{
$category->name = $bag->name;
$category->mm_name = (empty($bag->mm_name))?$bag->name:$bag->mm_name;
$category->save();
}
}
But it still throwing this error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list' (SQL: update `categories` set `name` = sdsd, `mm_name` = sdsd, `updated_at` = 2016-02-20 11:36:41 where `id` = 4)
I overrode the other tables and eloquent entity like that. That is all working, but this one is not. How can I fix that?
This is the screenshot of categories table:
If you're not using the created_at or updated_at fields, you need to set the $timestamps property on your model to false. Additionally, you don't need to override the setUpdatedAt() or setCreatedAt() methods.
class Category extends Model
{
protected $fillable = ['name', 'mm_name'];
public $timestamps = false;
}
If $timestamps is true, the Eloquent query builder will add in the updated_at field whenever you update a model.
Your mutator defination is wrong. it should be setUpdatedAtAttribute
and setCreatedAtAttribute
There was no need to delete the updated_at and deleted_at attributes from the database.
You have deleted the attributes from the database so there is no need for setUpdatedAtAttribute and setCreatedAtAttribute in your model. Laravel will include them as columns in your database.
Will advice you recreate the updated_at and created_at in the categories table and if you are using mysql 5.7 ensure that your timestamps are not 00-00-00 00:00:00 that is if you are manually created them(not recommended to manually create them).

Categories