I need help with table name in laravel 5.4 please.
I have a table called product_categories and a model called ProductCategory.
In the model I specify: protected $table = 'product_categories';
When I try to save a category I get this error:
Base table or view not found: 1146 Table 'highland.product-categories' why is it looking for a table called product-categories?
Thanks
Ok, found the problem, it was in my validation, checking for unique name:
'name' => 'required|unique:product-categories|string'
Changed it to:
'name' => 'required|unique:product_categories|string'
Related
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)"
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 2 tables one of images that belong to several different tables and in the other table the reference for id_imagen with the id of the table images.
Table Documentos:
id | id_imagen | titulo | texto
Table Imagenes:
id | tabla | imagen | tipo
Relationship:
Doumentos.id_imagen = Imagenes.id
In the model of images I have put:
$this->belongsTo('Escudos', [
'className' => 'Documentos',
'foreignKey' => 'id_imagen',
'conditions' => ['tabla' => 'escudos']
]);
In the model of documentos I have put:
$this->hasOne('Imagenes');
In the documentos controller:
$imagenes = TableRegistry::get('Imagenes');
$documentos = TableRegistry::get('Documentos');
$documentos = $imagenes->$documentos
->find('all')
->select(['Documentos.id', 'Documentos.titulo', 'Documentos.texto', 'Imagenes.imagen'])
->all();
$this->set('documentos', $documentos);
I get the following error:
Warning (4096): Object of class App\Model\Table\DocumentosTable could not
be converted to string [APP/Controller/DocumentosController.php, line 21]
Look at what you are doing in line 21:
$imagenes->$documentos
You are passing $documentos as the propery name to access on $imagenes, that's of course not going to work, as $documents is an object, as the error message suggests.
The documentos variable shouldn't be there in the first place. You want to query on $imagenes:
$imagenes->find()->/* ... */
Besides that your associations are not setup correctly, the Escudos association must be hasOne (the other table has the foreign key), and the Imagenes association must be belongsTo (the current table has the foreign key). Also as you are using non-conventional column names, you must at least configure the foreign key for the Imagenes association too.
Cookbook > Database Access & ORM > Associations - Linking Tables Together
In the end I found the solution:
Documentos table:
$this->hasOne('Imagenes')
->setBindingKey('id_imagen')
->setForeignKey('id');
Imagenes table:
$this->belongsTo('Documentos')
->setForeignKey('id_imagen')
->setJoinType('INNER');
Documentos Controller:
public function Documento() {
$documentos = TableRegistry::get('Documentos');
$documentos = $documentos->find('all')
->contain(['Imagenes']);
$this->set('documentos', $documentos);
}
view:
<?= $documento->imagen->imagen; ?>
In my user model I have added custom attribute get number of post user have created.
I can successfully get that but when I have try to order by it give error.
1054 Unknown column 'posts' in 'order clause'
Can you let us know what is the Eloquent query you're running? Also make sure that the name of the table you're using is correct.
EDIT:
Does the posts column exist in the users table? Or are you trying to get all the posts from the Post Model and order the posts by their name in descending order?
If that is what you want to do then you would need to go to your User Model and set up your relationship with posts.
In User Model create this method:
public function posts() {
return $this->hasMany('Post'); // Post would be the name of the Posts Model
}
In Post model do this:
public function user() {
return $this->belongsTo('User'); // Where User is the name of the Users Model
}
Then according to the Laravel documentation you could do someonething like this with the query:
$users = User::with(array('posts' => function($query)
{
$query->orderBy('name', 'desc'); // assuming that 'name' would be the column in the posts table you want to sort by
}))->take(5)->get();
I hope I am correct and this helps and that solves your issue.