Cakephp 3 - Save associated belongsToMany (joinTable) - php

i have a question about saving a new entity with an association which is a belongsToMany relation. Just a quick introduction. I have something like a settings table and a setting_values table. The user is connected to the settings by a joinTable called users_settings. So in summary:
settings:
id | name
setting_values:
id | setting_id | name | value |
users_settings:
id | user_id | setting_id | setting_value_id
Now before the user is added I want to patch the entity of the user with all settings and the first setting_value for each setting. So that users_settings has now all settings connected to the user with the first value. But I can't get the patch or the newEntity to be work. All models are baked so this should be fine. Here's my code
$settings = $this->Settings->find('all', [
'contain' => [
'SettingValues'
]
]);
$settingsData = [];
foreach ($settings as $setting) {
$settingsData[] = [
'setting_id' => $setting->id,
'setting_value_id' => $setting->setting_values[0]->id,
];
}
$data = [
'users_settings' => $settingsData
];
$user = $this->Users->patchEntity($user, $data, [
'associated' => [
'Settings.UsersSettings'
]
]);
This is the result in the $user entity. As you can see nothing is corretly marshaled:
users_settings => [
(int) 0 => [
setting_id => (int) 1,
setting_value_id => (int) 1
],
(int) 1 => [
setting_id => (int) 2,
setting_value_id => (int) 5
]
]
Can someone give me an advice on this. Thanks

That's not how belongsToMany association data should be structured, you have to supply the target, not the join table. Additional join table data can be supplied via the special _joinData key, ie the data should look like:
$data = [
'settings' => [
[
'id' => 1,
'_joinData' => [
'setting_value_id' => 1
]
],
[
'id' => 2,
'_joinData' => [
'setting_value_id' => 5
]
]
]
];
That would populate the join table like:
+----+---------+------------+------------------+
| id | user_id | setting_id | setting_value_id |
+----+---------+------------+------------------+
| 1 | 1 | 1 | 1 |
| 2 | 1 | 2 | 5 |
+----+---------+------------+------------------+
And if you (need to) use the associated option, then make sure to specify the _joinData key too:
$user = $this->Users->patchEntity($user, $data, [
'associated' => [
'Settings._joinData'
]
]);
See also
Cookbook > Database Access & ORM > Saving Data > Saving BelongsToMany Associations
Cookbook > Database Access & ORM > Saving Data > Saving Data To The Join Table

Related

Using select2_from_ajax with a JSON datasource

I am new to Laravel and to Backpack for Laravel so please bear with me. I am trying to create a client registration form that features a "State" field which is populated dynamically depending on the value selected for the "Country" field.
I am following the instructions provided by Backpack's author here: https://backpackforlaravel.com/docs/3.5/crud-fields#select2_from_ajax
Both states and countries come from this dataset: https://github.com/antonioribeiro/countries. They are returned as collections but they are not read from the DB.
Table schema for Clients (simplified)
+-------------------+---------+--------+
| Field | Type | Length |
+-------------------+---------+--------+
| uuid | CHAR | 36 |
| name | VARCHAR | 128 |
| city | VARCHAR | 128 |
| state | VARCHAR | 64 |
| country_iso_cca2 | VARCHAR | 2 |
+-------------------|---------+--------+
The good part
The "Country" field works just fine. It fetches data from the JSON dataset at creation and reads/writes info from or to the DB on update/save:
// ClientCrudController.php
$countries = new Countries();
$allCountriesCodes = $countries->all()->pluck('name.common', 'cca2')->toArray();
$this->crud->addField([
'name' => 'country_iso_cca2',
'label' => 'Country',
'type' => 'select2_from_array',
'options' => $allCountriesCodes,
'allows_null' => false,
'default' => 'US',
]);
The bad (incomplete) part
// ClientCrudController.php
$this->crud->addField([
'name' => 'state',
'label' => 'State',
'type' => 'select2_from_ajax',
'entity' => 'foobar', // the method that defines the relationship in your Model
'attribute' => 'name',
'data_source' => url('api/states'),
'placeholder' => 'Select a country first...',
'dependencies' => ['country_iso_cca2'],
]);
Calling /admin/client/create will result in an error ("Call to undefined method App\Models\Client::foobar").
I understand that the error is raised because there is no model defined for States and hence no relationship. My problem is, I do not understand what the implementation is supposed to look like in a case like this where the two select fields do not represent separate entities at an ORM level.
Is it possible to implement this kind of dependency in a "backpack-native" way, without resorting to creating a custom field type?

CakePHP contain() method sees belongsToMany over belongsTo of same table

So I have the following (simplified) model
+------------------+
| project_statuses |
+------------------+
+---------------------+ +----| id |
| projects | | | name |
+---------------------+ | +------------------+
| id | | +---------+
| name | | | clients |
| project_statuses_id |----+ +---------+
| client_id |---------| id |
+---------------------+ | name |
| +---------+
+------------------+ |
| clients_projects |------+
+------------------+
| id |
| client_id |
| project_id |
+------------------+
where a project belongs to many clients and a client can have many projects, but only one client (Projects.client_id) can take the responsibility for a project. The project status is here just for comparision.
So the associations in my ProjectsTable.php, ClientsTabe.php and ProjectStatusesTable.php look like this
// In ProjectsTable.php
$this->belongsTo('ProjectStatuses', [
'foreignKey' => 'project_status_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Clients', [
'foreignKey' => 'client_id',
'joinType' => 'INNER'
]);
$this->belongsToMany('Clients', [
'foreignKey' => 'project_id',
'targetForeignKey' => 'client_id',
'joinTable' => 'clients_projects'
]);
// In ClientsTabe.php
$this->hasMany('Projects', [
'foreignKey' => 'client_id'
]);
$this->belongsToMany('Projects', [
'foreignKey' => 'client_id',
'targetForeignKey' => 'project_id',
'joinTable' => 'clients_projects'
]);
// In ProjectStatusesTable.php
$this->hasMany('Projects', [
'foreignKey' => 'project_status_id'
]);
Now in my projects/index page I'd like to have a table showing the project id, name, status and responsible. So I thought in something like this
// In ProjectsController.php
$this->Projects->find()->select(['Projects.id','Projects.name'])
->contain(['ProjectStatuses' => [
'fields' => [
'ProjectStatuses.name',
]]])
->contain(['Clients' => [
'fields' => [
'Clients.name',
]]]);
But only ProjectStatuses.name is fetched, for Clients.name it throws the error You are required to select the "ClientsProjects.project_id" field(s) telling me that is looking through the belongsToMany association rather than the belongsTo one.
In fact, if I just write ->contain('Clients') instead of specifying the Clients.name field it send the following queries
SELECT
Projects.id AS `Projects__id`,
Projects.name AS `Projects__name`,
ProjectStatuses.name AS `ProjectStatuses__name`
FROM
projects Projects
INNER JOIN project_statuses ProjectStatuses ON ProjectStatuses.id = (Projects.project_status_id)
SELECT
ClientsProjects.id AS `Clients_CJoin__id`,
ClientsProjects.client_id AS `Clients_CJoin__client_id`,
ClientsProjects.project_id AS `Clients_CJoin__project_id`,
Clients.id AS `Clients__id`,
Clients.name AS `Clients__name`,
FROM
clients Clients
INNER JOIN clients_projects ClientsProjects ON Clients.id = (ClientsProjects.client_id)
WHERE
ClientsProjects.project_id in (4)
How can I tell the query object to get the Clients.name through Projects.client_id just as I get ProjectStatuses.name through Projects.project_statuses_id instead of passing by the ClientProjectstable?
In your Projects table, you have created two associations for Clients, and vice versa. That doesn't work (as The Highlander said, "There can be only one"), and is likely the source of all your problems.
You'll need to change one of those associations in each table. Maybe a Project should belongsToMany Clients but only belongTo one ResponsibleClient, and a Client should belongsToMany Projects and hasMany ReponsibleProjects?

cakephp 3 paginate sort custom field

i try to sort "hasMany" associate
this is my code :
Advisor Modal
$this->hasMany('AdvisorNotes', [
'foreignKey' => 'id',
'sort' => [
'created' => 'DESC',
],
'joinType' => 'LEFT',
]);
Advisor Controller
public function index() {
$this->paginate = [
'contain' => [
'Branch' => [ 'BranchCity', 'Bank' ],
'AdvisorLevel',
'AdvisorRelation',
'UsersAgent',
'AdvisorNotes'
],
'sortWhitelist' => [
'BranchCity.city_name',
'Branch.name',
'Advisor.name',
'AdvisorRelation.relation',
'AdvisorLevel.level',
'Advisor.telephone',
'UsersAgent.name',
'AdvisorNotes.created',
'Bank.name',
]
];
$advisors = $this->paginate( $this->Advisor );
AdvisorNotes table
id | advisor_id | agent_id | type_id | note | created
Advisor table
id | name | image | date_of_birth | important_date | branch_id | telephone | fax | cellphone | email | description | level_id | relation_id | agent_id | agent_admin_id | created
i try to make field in the Advisor index that show the last AdvisorNote and be able to sort it.
as you can see AdvisorNotes as advisor_id in table but Advisor dont have any id of the AdvisorNotes.
thanks.

No searching on primary key with Laravel Scout?

I'm using Laravel Scout with TNTSearch Engine at it's working fine but with one little problem. I have the following records.
| ID | Name |
+---------+----------+
| 9030100 | Car |
| 9030150 | Car2 |
| 9030200 | Radio |
Here is my query:
CatalogProducts::search( $query )->paginate( 15 );
When I'm looking for 'car,' it's returning all records with 'car' in the name.
When I'm looking for '9030100', it's returning the product 'Car.'
But when I'm looking for '9030', I don't have any results. Why? How do I fix it?
try changing the fuzziness.
set fuzziness to true.
'tntsearch' => [
'storage' => storage_path(), //place where the index files will be stored
'fuzziness' => true,
'fuzzy' => [
'prefix_length' => 2,
'max_expansions' => 50,
'distance' => 2
],
'asYouType' => false,

CakePHP empty Fields of associations are saved instead of discard

I have a small project on CakePHP. It has a table named articles, and 5 tables of Fields like categories, tags, images, etc. The associations are mostly HasOne, and associated tables has multiple column.
When saving data on articles table everything look good, but on some associations, for example: Article -> Rating, if I did not fill up some fields of Rating tables, that are being saved as null:
+----+------------+--------------+
| id | article_id | rating_value |
+----+------------+--------------+
| 1 | 36 | 3 |
| 2 | 56 | 5454.56 |
| 3 | 57 | 4 |
| 5 | 51 | NULL |
+----+------------+--------------+
If I add some validations, then I can't save the article as it need to be validated. All I want is that if rating_value is empty, then it must not be created as null (entity rejected), and the article must be saved.
Deleting articles works as expected, all related entities are deleted.
I tried altering $data on Model.beforeMarshall but the class is private in both Tables Articles and Ratings (i think associations may be the problem).
Some code (controller add):
public function add()
{
$article = $this->Articles->newEntity();
if ($this->request->is('post')) {
$article = $this->Articles->patchEntity($article, $this->request->data, [
'associated' => [
'Ratings',
]
]);
if ($this->Articles->save($article)) {
$this->Flash->success(__('Saved.'));
return $this->redirect(['action' => 'index']);
}
}
$this->set('article', $article);
}
I deleted all validations of every associated Model because of this.
// Articles Table
$this->hasOne('Ratings', [
'className' => 'Ratings',
'dependent' => true,
]);
// Ratings Table
$this->belongsTo('Articles', [
'foreignKey' => 'article_id',
'joinType' => 'INNER'
]);
// Rating.php Entity
protected $_accessible = [
'*' => true,
'id' => false
];
// Article.php Entity
protected $_accessible = [
'*' => true,
];
If you are setting rating_value then it will try to save and validate with all validation rules.
You can remove the associated data if rating_value is empty like this
$dataToSave = $this->request->data;
if(empty($dataToSave['rating']['rating_value'])){
unset($dataToSave['rating']);
}
$article = $this->Articles->patchEntity($article, $dataToSave, [
'associated' => [
'Ratings',
]
]);
I thing every thing looks good.May be your field in table has default value as null. For example:
If 'rating_value' field in your table has default value null,
make that default full to none first.
If validation fails that don't give you save anything rather than saving null value.If that still don't work for you see:
debug($this->request->data);
And look there if data are coming correctly from your view(form).
Another important thing is that you can use different validation set for association. (see here)

Categories