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.
Related
Trying to update a table that holds a user's settings. I have a hasOne usersetting relation setup in the user model. The usersetting table doesn't have a id column. But Im getting this error.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where
clause' (SQL: update usersettings set user_name = u9ddf,
usersettings.updated_at = 2019-04-30 02:13:37 where id is null).
public function profileupdate(Request $request)
{
if($user = Auth::user())
{
$usersetting = $user->usersetting;
$usersetting->update([
'user_name' => $request->input('profile_name')
]);
return redirect('profilesettings');
}
}
I guess Im not querying correctly with eloquent?
Add the following in model usersetting:
protected $primaryKey = 'user_id';
I figured it out. Had to set user_id as a primary key in usersetting model.
public $primaryKey = 'user_id';
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());
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).
I am new to laravel and using Eloquent ORM. Now the issue is I am trying to get records using relationships with with() function. Now this issue is that eloquent generates and applies the right query but does not returns any result. But if I test the same generated query on mysql than it works fine.
Following are the two tables that are involved in this:
Properties:
id , name , locality_id
Localities:
id, name , type , adjoining
Now the relationship between above mentioned tables is one to many relationship.
Property Model:
protected $table = 'properties';
protected $guarded = array('id');
public function localityAreaAndCity() {
return $this->belongsTo('Locality','locality_id')
->leftjoin('localities as ls', function($join)
{
$join->on('localities.id', '=', 'ls.adjoining')
->where('localities.type', '=','area');
});
->select(array('localities.name as localityPrimaryName',
'localities.type as localityPrimaryType',
'ls.name as localitySecondaryName',
'ls.type as localitySecondaryType'));
}
Locality Model:
public $timestamps = false;
protected $table = 'localities';
protected $guarded = array('id');
public function properties()
{
return $this->hasMany('Property');
}
Eloquent Query:
$properties = Property::with('localityAreaAndCity')->get();
DB::getQueryLog() Result:
select `localities`.`name` as `localityPrimaryName`, `localities`.`type` as `localityPrimaryType`, `ls`.`name` as `localitySecondaryName`, `ls`.`type` as `localitySecondaryType` from `localities` left join `localities` as `ls` on `localities`.`id` = `ls`.`adjoining` and `localities`.`type` = ? where `localities`.`id` in (?, ?, ?, ?, ?)
Know if I use the above mentioned query in mysql then it returns data but using with Eloquent ORM it returns NULL.
Please Help..
Just added locality_id to the select and it worked. Actually eloquent works like you have 2 arrays with related items and you want to match them - if there's no foreign key in one of them, that points to the primary key in the other one, then you can't do that. Eloquent does exactly the same.
You must always select both keys of the relation (most likely PK on one model and FK on the other one).
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');