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)"
Related
I have a table with columns like "name", "surname", "user_id", and I need to check if entry exists first by id, and then by name and surname together, if there is none, create it. How do I do it neatly, instead of making two update statements, and if both return 0 just create a new one (which seems too bulky)
I thought of using firstOrNew, but it seems that it only can work while matching all of the parameters.
Is there any method I've missed that would apply well to my situation?
You could try something like this (assuming you want to create a model [saved to the database]):
$attributes = [
'name' => ...,
'surname' => ...,
];
$model = Model::where('id', $id)
->orWhere(fn ($q) => $q->where($attributes))
->firstOr(fn () => Model::create($attributes));
This would search for a record by id OR name and surname. If it doesn't find one it will create a new record with the name and surname (assuming those attributes are fillable on the Model).
Laravel 8.x Docs - Eloquent - Retrieving Single Models / Aggregates firstOr
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()
When using the select2 field/column type in Laravel Backpack, the list view displays the 'id' of the foreign entity instead of the foreign key required (in this case the 'name' of the Session).
Laravel 5.8.4, Backpack 3.4. I asked in GitHub and the response was that my relationships were incorrect in my models. I don't think that's the problem as the name loads in the edit view.
GradeCrudController
$this->crud->addColumn([
'label' => "Session",
'type' => 'select2',
'name' => 'session_id', // the db column for the foreign key
'entity' => 'session', // the method that defines the relationship in your Model
'attribute' => 'name', // foreign key attribute that is shown to user
'model' => "App\Models\Session" // foreign key model
]);
Grade (Model)
public function session()
{
return $this->belongsTo('App\Models\Session');
}
Session (Model)
public function grades()
{
return $this->hasMany('App\Models\Grade');
}
As it's been a few days and nobody has responded, I thought I'd post the answer I came up with. Note that I highly doubt that this is the correct solution, but for my project it will do.
I added a Laravel Observer for the Grade Model. Once a user adds a new record, the observer visits the session table, pulls the name of the session using the key and adds it as a column to the Grades table.
Then in backpack I just display the 'name' column.
There has to be a better way than this... But for now it will do.
I see you're using a "select2" column type. That's not something Backpack provides by default - it only has a "select" column.
Most likely what happened is that Backpack loaded the "text" column, since it couldn't find a "select2" column. Hence, the ID.
Try changing "select2" to "select". It should work for you without any observers/anything else.
I was having a similar issue. I could not get the foreign key attribute to show up no matter what. I finally got it working by doing to following.
Add the foreign key to the belongsTo method. It should be the name of the column in that model that has the ID that is associated with in the belongsTo model.
public function session()
{
return $this->belongsTo('App\Models\Session','name');
}
One other item that I suggest is to make sure all columns that have foreign keys are set to the same data types in the database.
I have table 3 tables, equipment(ID, name)
parameters(ID, name) and the pivot table equipment_parameter(equipment_id, parameter_id) , on my "Equipment" list view i need to add a column with the name of the parameter so i need to retrieve name from the Parameter table.
Equipment Model:
public function parametros(){
return $this->belongsToMany('App\Parametro','equipo_parametro','equipo_id',
'parametro_id')->withTimestamps();
}
Parameter model:
public function equipos(){
return $this->belongsToMany('App\Equipo','equipo_parametro','parametro_id',
'equipo_id')->withTimestamps();
}
i added this on equipmentCrudcontroller ,but have had no success.
$this->crud->addColumn([ // Select
'label' => 'Parametro',
'type' => 'select2',
'name' => 'equipo_id', // the db column for the foreign key
(not sure here since equipment foreign key is on pivot table????)
'entity' => 'parametros', // the method that defines the relationship in your Model
'attribute' => 'nombre', // foreign key attribute that is shown to user
'model' => "App\Parametro" // (doubt, there's a pivot table inbetween???) foreign key model
]);
If you are adding a column and have already run the previous migration you can create a new migration php artisan make:migration update_equipment_table inside of that, you can then do something like this
Schema::table('table', function (Blueprint $table) {
$table->string('column');
});
then rerun migrations php artisan migrate this will add the new column to your table.
I have two models : Event and Soundcloud.
Both are defined to be a many-to-many relationship in Laravel and it is working fine.
I am saving the soundcloud and population the pivot table event_soundcloud by doing this
foreach ($data as $artist => $url) {
$soundcloud = Soundcloud::firstOrNew(['artist_name' => $artist, 'link' => $url]);
$event->soundclouds()->save($soundcloud);
}
That function is called every 10 minutes and each time the same records are added to the pivot table.
Is there a way to do the same thing but adding records in pivot table only if it does not exist already ?
Thank you
Here is what I did to make it work. I guess you cannot do it in one step
$soundcloud = Soundcloud::firstOrNew(['artist_name' => $artist, 'link' => $url]);
$soundcloud->save();
$event->soundclouds()->sync([$soundcloud->id], false);