Laravels's Eloquent "create" method tries to save empty attributes - laravel

class Setting extends Eloquent {
public $primaryKey = 'key';
public $timestamps = false;
public $fillable = array('*');
}
My table settings consists of 2 columns: key and value.
When I try to execute:
Setting::create(array(
'key' => 'test',
'value'=> 'test1'
));
I get:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'PRIMARY' (SQL: insert intosettings() values ()) (Bindings: array ( ))
which is extremely weird. Any ideas? I tried this on 2 tables, it has the same problem. My Laravel version is up to date.

Could you please show you database table definition. Are you sure that 'key' is really set as PRIMARY key in your table? The first thing came to my mind is that you probably have different field set as PRIMARY in your 'settings' table ('id' or something) and you didn't set 'auto_increment' flag for that field.

Related

OctoberCMS belongsTo relationship saving problem

I have two models:
Brands
Mods
I can display all brands via belongsTo function. Problem is when I try to save same brand two times, I get error duplicated entry.
This belongsTo is causing duplicated entry error when saving to DB two same brands.
Mods.php
public $belongsTo = [
'brand' => [\Slasher\Farming\Models\Brands::class, 'key' => 'id'],
];
This belongsToMany works, and save's data to DB, but is generating checkbox field (I only want to select one brand at one mod enty). I'm using pivot table for this relation.
Mods.php
public $belongsToMany =[
'brand' =>[
'Slasher\Farming\Models\Brands',
'table' => 'slasher_farming_mods_brands',
'order' => 'brand_name'
],
];
BelongsTo example: (Brands are visible and I can save them. But problem is when saving same brand for more than two times).
Error I get when saving with belongsTo.
I tried also creating inverse relationships on Brands model with (belongsTo and belongsToMany), but still getting this error.
What type of relation should I make, to save Brands as dropdown list and to fix this duplicate error?
If you're using a pivot table for your relation, then you should use $belongsToMany. Pivot table is only used for many-to-many relations.
I fixed this problem with changing column in the mods name brand to brand_id and also changing belongsTo relation. I just removed key, and it works like a charm. No need for pivot table here.
Mods.php
public $belongsTo = [
'brand' => ['Slasher\Farming\Models\Brands']
];
"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3' for key 'PRIMARY' (SQL: update liam_blog_blogs set id = 3, liam_blog_blogs.updated_at = 2022-07-26 09:30:09 where id = 2)"

Issue while trying to search using whereBetween in Laravel Eloquent

I have 2 database tables in MySQL below.
Table - 1
CREATE TABLE `tblaccount` (
`account_id` mediumint(8) UNSIGNED NOT NULL,
`account_number` varchar(100)
)
ALTER TABLE `tblaccount`
ADD PRIMARY KEY (`account_id`);
Table - 2
CREATE TABLE `tblcollectoractions` (
`collector_action_id` mediumint(8) UNSIGNED NOT NULL,
`account_id` mediumint(8) UNSIGNED DEFAULT NULL,
`pay_date` date DEFAULT NULL
);
ALTER TABLE `tblcollectoractions`
ADD PRIMARY KEY (`collector_action_id`),
ADD KEY `tblcollectoractions_account_id_foreign` (`account_id`);
I have a query below. It joins records in both tables on the basis of account_id. It also filters those accounts in tblcollectoractions table where pay_date lies between start and end date.
Here is my Laravel Eloquent Query. AccountModel is related to tblaccount and ActionModel is related to tblcollectoractions.
$query = (new AccountModel())->newQuery();
$data->whereIn("account_id", function($query) use($inputs) {
$query->select('account_id')->from(with(new ActionModel)->getTable())
->whereBetween('pay_date', [$inputs["from_pay_date"], $inputs["to_pay_date"]]);
});
But, this shows me all the records from table tblcollectoractions. I meant, it does not filter on the basis of start and end date.
Am I missing anything?
This is the most Eloquent way to do this, checking if the $inputs variable is set
$data = AccountModel::query()
->with([
'actions' => function($query) use ($inputs) {
if ($inputs['from_pay_date']) {
$query->whereBetween('pay_date', [
$inputs['from_pay_date'],
$inputs['to_pay_date']
]);
}
}
])
->has('actions')
->get();
the models should look something like this:
AccountModel.php
class AccountModel extends Model
{
protected $guarded = ['id'];
public function actions()
{
return $this->hasMany(ActionModel::class, 'account_id', 'account_id');
}
}

Why last id is lost while creating process?

I have a create method that works fine, but it fails trying to create its relation:
public function create(array $article, string $note)
{
$art = $this->article->create($article);
print($art->id) // this line is for helping me to know if id is successfully generated. It works!
$this->article->note()->create([
'article_id' => $art->id, // the id desapears
'note' => $note
])
}
Console logs:
Integrity constraint violation: 1048 Column 'article_id' cannot be null (SQL: insert into notes (article_id, note, updated_at, created_at) values (?, TESTING, 2019-11-13 13:03:07, 2019-11-13 13:03:07))"
The field article_id is probably not a fillable attribute on the Note model.
You could also create the note like this, without adding article_id as a fillable attribute:
$art->note()->create([
'note' => $note
]);
Also make sure that the relations are defined correctly on the models. If an article can have many notes, there might be something wrong with your definitions, since note is currently singular. If it is a one to one relation everything might be fine.
You need to save your article. $art->save()

$fillable and create() not working

I've just installed new laravel project. After that, I created new Model but when I use create() function, it just show me that my new rows has been duplicated.
This is my code:
protected $fillable = ['id', 'setting_name', 'expected_type', 'default_val', 'modified_val'];
// protected $guarded = ['created_at', 'updated_at'];
function test() {
$input = ['setting_name' => 'Test',
'expected_type' => '123',
'default_val'=>'123',
'modified_val'=>'123'];
// dd($input);
//both next two lines do not working
Setting::create($input);
return Setting::firstOrNew($input);
}
I checked the error :
"Integrity constraint violation: 1062 Duplicate entry '' for key 'setting_name' (SQL: insert into settings (updated_at, created_at) values (1474452834, 1474452834))"
What i did wrong ?
At the end of the day, I realized that I created __constructor for my model, that why I could not create object normally.
I removed that constructor and it works well. :D
The error says you're trying to insert row with setting_name which is already exists in a table and you have unique constraint for this column.
So, make sure you're inserting this row only once and there is no any other row with the same setting_name value.

Laravel - Many to Many Polymorphic Relation with Extra Fields

How can I define a many to many polymorphic relation with extra fields?
I have three (or more, as it is a polymorphic relation) tables.
tags table: id, name
tagged table: id, tag_id, taggable_id, taggable_type, user_id
posts table: id, record, timestamps
users table: id, name, email
The user_id on the tagged table referes to the users table on column id.
In my Post model I have:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable','tagged');
}
and in my Tag model I have:
public function posts()
{
return $this->morphedByMany('App\Post', 'taggable','tagged');
}
Then when I am try this in my controller:
$tag = new \App\Tag(
array(
'tag'=>"someTag"
));
$tag->save()
$post = \App\Post::find($id);
$post->tags()->save($tag);
I get Integrity Constraint Violation for not having a user_id:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (hb.tagged, CONSTRAINT tagged_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id)) (SQL: insert into tagged (tag_id, taggable_id, taggable_type) values (26, 2, App\Resource)).
Which is somewhat expected, as I have never had the chance to define or declare the user_id field.
Also, I have tried withPivot() on tags relation as follows, to no avail:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable','tagged')->withPivot('user_id');
}
Like in the comment: withPivot has nothing to do with saving/creating. If you want to pass additional pivot data when saving, do this:
$post->tags()->save($tag, ['user_id' => $userId]);

Resources