How to setup these relations correct in Backpack for Laravel - laravel-backpack

I have a Problem with relations in Laravel / with Backpack for Laravel.
This program is for creating menues for my dad´s restaurant.
I have these tables:
- dishes (Table with the Names of the Dishes)
-- id (auto inc)
-- menuname (Name of the Dish)
- weeklymenues
-- id (auto inc)
-- start_date (Monday of the selected week)
-- end_date (Friday of the selected week)
-- menu_monday (There should be the id of the dish)
-- menu_tuesday (...)
-- menu_wednesday (...)
.....
How can i do that correctly?
In the CRUD Controller i am setting the Field:
$this->crud->addField([
'label' => "Monday",
'type' => 'select2',
'name' => 'menu_mondy', // the db column for the foreign key
'entity' => 'menu', // the method that defines the relationship in your Model
'attribute' => 'menuname', // foreign key attribute that is shown to user
'model' => "App\Models\Menu" // foreign key model
]);
And in the menues model i have set this relation:
public function menu() {
return $this->belongsTo('\App\Models\Menu');
}
Everytime I want to save the CRUD, the program wants to save something in the dishes table:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'dish_id' in 'field list' (SQL: update `weeklymenues` set `dish_id` = 1, `weeklymenues`.`updated_at` = 2019-06-25 14:13:14 where `id` = 15)
What am I doing wrong? How can I set the relations correct?
Thanks in advance!!

Are "dishes" (from the table definition) and "Menu" (from the code) actually the same thing?
In your field definition, you set the model to be the "menu" class, shouldn't it be the "dishes" class?
I would have used the relationship type
CRUD::addField([
'label' => 'Monday',
'type' => 'relationship',
'name' => 'menu', // the method that defines the relationship in your Model
'attribute' => 'menuname', // foreign key attribute that is shown to user
'model' => \App\Models\dishes::class, // foreign key model
'placeholder' => 'Select a dish for Monday'
]);

---
-c:\xampp\htdocs\bpwebsite\app\Models\weeklymenues.php
---
protected $fillable = ['start_date', 'end_date', 'menu_monday']
---

Related

how to create dependent select using backpack-for-laravel?

How to create a dependent select like country / city relationship using backpack-for-laravel?
Like: just show cities for the selected country
$this->crud->addField([ // Select2
'label' => "country",
'type' => 'select2',
'name' => 'country_id', // the db column for the foreign key
'entity' => 'country', // the method that defines the relationship in your Model
'attribute' => 'country', // foreign key attribute that is shown to user
'model' => "App\Models\Country" // foreign key model
]);
$this->crud->addField([ // Select2
'label' => "City",
'type' => 'select2',
'name' => 'city_id', // the db column for the foreign key
'entity' => 'city', // the method that defines the relationship in your Model
'attribute' => 'city', // foreign key attribute that is shown to user
'model' => "App\Models\City" // foreign key model
]);
There is a feature for that, but is not merged yet. You may take a look at [Feature][3.4][Ready] Select2_from_ajax can depend on any other input and check it out the modified files and reproduce in your installation.

multiple attributes in select2 field type

I'm trying to set more than one attribute in a select2 type field.
For Example, I would like to show first_name and last_name as the label of my select values:
$this->crud->addField([ // Select
'label' => 'Employer',
'type' => 'select2',
'name' => 'employer_id', // the db column for the foreign key
'entity' => 'employer', // the method that defines the relationship in your Model
'attribute' => 'first_name', // foreign key attribute that is shown to user
'model' => 'App\Models\Employer' // foreign key model
], 'update/create/both');
Is there any suggestion?
Thanks.
You can with a getter:
public function getIdentNameAttribute()
{
return "{$this->ident} {$this->name}";
}
Then in your controller use:
"attribute" => "IdentName", // foreign key attribute that is shown to user

FuelPHP ORM Primary Key on model cannot be changed

I've been banging my head with this ORM error:
Fuel\Core\FuelException [ Error ]: Primary key on model Model_CustomValue cannot be changed.
Here are relevant info from my models I'm having issues with:
<?php
use Orm\Model;
class Model_Purchase extends Model
{
protected static $_has_many = array(
'customvalues' => array(
'model_to' => 'Model_CustomValue',
'key_to' => 'purchase_id',
'cascade_delete' => true,
)
);
protected static $_properties = array(
'id',
'customer_id',
'payment_id',
'audit_id',
'created_at',
'updated_at',
);
<?php
use Orm\Model;
class Model_CustomValue extends Model
{
protected static $_table_name = 'customvalues';
protected static $_primary_key = array('purchase_id', 'customfield_id');
protected static $_belongs_to = array(
'purchase' => array(
'key_from' => 'purchase_id',
'model_to' => 'Model_Purchase',
'key_to' => 'id',
),
);
When trying to save the Model_Purchase with an array of Model_CustomValue objects as a property named 'customvalues' on the $purchase object, I get the "Primary key on model Model_CustomValue cannot be changed."
I've tried swapping the key_from/to in the "belongs_to" on the Model_CustomValue, but to no avail.
I'm using Fuel 1.6 (hash: 6e6d764)
Please let me know if more information would be helpful, and I'll provide.
From the FuelPHP forum thread, Harro answered:
You can not have a column which is at the same time FK and PK. Which
you have on your Model_CustomValue.
The reason for that is that when you disconnect a relation, the FK
will be set to NULL, which should not happen with a PK.
I then clarified, for those of us who may need specific examples from the original example, I confirmed the following:
So just re-stating why that's not allowed:
Model_CustomValue uses the "purchase_id" as part of its PK as well as the FK to Model_Purchase. And if the two Models were to be unlinked, that would lead to a null portion of the PK for Model_CustomValue -- which obviously isn't allowed.

Cakephp automatically filled form select for two word named belongTo model

What is right naming or what am I missing to get automagic run for two word named Model. Actual model belong to the two words named model.
Exact example:
Tour belongs to Accommodation type.
in database there is table tours and table accommodation_types
foreign key from tours is tours.accommodation_type_id
Snapshots of code below.
ToursController.php
public function add() {
//...
$accommodation_types = $this->Tour->AccommodationType->find('list');
//...
$this->set(compact('accommodation_types', ...));
}
Tour.php
//...
public $belongsTo = array(
//...
'AccommodationType' => array(
'className' => 'AccommodationType',
'foreignKey' => 'accommodation_type_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
//...
);
Tours/add.ctp (inside a form)
echo $this->Form->input('accommodation_type_id', array('label' => 'Accommodation type'));
As per convention the view vars names should be camelBacked. So rename the view var from $accommodation_types to $accommodationTypes. If you don't follow convention you have to explicitly specify the options var to use like this:
echo $this->Form->input('accommodation_type_id', array('options' => $accommodation_types, 'label' => 'Accommodation type'));

CakePHP 2.2 with PostgreSQL Failed new row insert - Database Error: Undefined table: 7 ERROR: relation "table_id_seq" does not exist

My problem is as follows.
After deleting multiple rows from table, inserting new record into same table results in error.
Database Error
Error: SQLSTATE[42P01]:
Undefined table: 7 ERROR: relation "order_details_id_seq" does not exist
Table
CREATE TABLE schema.order_details (
id serial NOT NULL,
order_id integer NOT NULL,
field_1 integer,
field_2 real,
field_3 character varying(15),
CONSTRAINT order_details_pkey PRIMARY KEY (id )
)
WITH (
OIDS=FALSE
);
Insert is
INSERT INTO "schema"."order_details" ("order_id", "field_1", "field_2", "field_3")
VALUES (37, 1, 2, 'value');
Sequence "schema"."order_details_id_seq" in used schema exists.
CREATE SEQUENCE schema.order_details_id_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 37
CACHE 1;
Models.
// Model
class Order extends AppModel {
public $useDbConfig = 'other_data';
public $hasMany = array(
'OrderDetail' => array(
'className' => 'OrderDetail',
'foreignKey' => 'order_id',
'dependent' => true,
'order' => array(
'OrderDetail.order_id',
'OrderDetail.field_1'
))
);
class OrderDetail extends AppModel {
public $useDbConfig = 'other_data';
public $belongsTo = array(
'Order' => array(
'className' => 'Order',
'foreignKey' => 'order_id',
'dependent' => true
),
// model Order save code on recreation of order
$this->OrderDetail->deleteAll(array('OrderDetail.order_id' => $this->id));
At this point tried to insert $this->OrderDetail->query('VACUUM FULL ANALYZE order_details'); with no effect
foreach ($details as $d) {
$this->OrderDetail->create();
$this->OrderDetail->save($d /*array(
'order_id' => $this->id,
'field_1' => 1,
'field_2' => 2,
'field_3' => 'value'
)*/);
}
I get error on first foreach loop.
Weirdest thing is that problem appears and disappears after some time randomly.
Any suggestions on what it could be and how to get rid of it?
Currently solved problem using code.
$this->Order->id = $id;
$this->Order->delete();
It fires 2 queries for each row (100 extra in my case!) of delete statements instead of two in case of
$this->OrderDetail->deleteAll(array('OrderDetail.order_id' => $id));
So for this time it has space for improvement.
EDIT: Currently code works as it should with tweaked DboSource.
It seems that cake was looking in public schema for sequence where it is not located.
Fixed it by tweaking to include schema name in last insert getter inf file Model/Datasource/DboSource.php create method with this diff
## -1006,7 +1006,7 ##
if ($this->execute($this->renderStatement('create', $query))) {
if (empty($id)) {
- $id = $this->lastInsertId($this->fullTableName($model, false, false), $model->primaryKey);
+ $id = $this->lastInsertId($this->fullTableName($model, false, true), $model->primaryKey);
}
$model->setInsertID($id);
$model->id = $id;
I know that modifying core is not the way to go, but as long as it is working it is fine with me.
This happened to me because I modified the name of the table, but PostgreSQL did not change the name of the sequences. Knowing this, I changed the name of the sequences that affected this table and it was resolved.
To prevent this error, use this convention to name your sequence when using cakephp: table_name_id_seq. For example:
table name: user
sequence name should be: user_id_seq
If you alredy have sequences, you can rename it in posgres like this
alter sequence user_seq rename to user_id_seq
I'm not a fun of this way to name sequence but it prenvent this kind of errors in my case