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.
Related
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?
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?
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
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,
I've got two mysql tables:
1. prices
2. details
Table Prices
ID | DATE | CODE | PRICE
1 |2014-01-01 | AAA1 | 90.123
2 |2014-01-01 | AAB1 | 50.113
3 |2014-01-01 | AAC1 | 48.621
4 |2014-01-02 | AAA1 | 91.123
5 |2014-01-02 | AAB1 | 51.113
6 |2014-01-02 | AAC1 | 41.621
Table Details
CODE | NAME | DESCRIPTION
AAA1 | andria | A very good...
AAB1 | anasta | A very good...
AAC1 | simple | A very good...
Models:
Prices
public function relations(){
return array(
'code' => array(self::BELONGS_TO, 'details', 'code'),
);
}
Details
public function relations(){
return array(
'code' => array(self::HAS_MANY, 'prices', 'code'),
);
}
Here's the SQL code I want to execute:
SELECT * FROM prices a
JOIN (SELECT * FROM details) b
WHERE a.DATE=(SELECT MAX(DATE) FROM prices) AND a.code = b.code
My controllers:
$prices=new CActiveDataProvider('prices', array(
'criteria'=>new CDbCriteria (array(
'select'=>'code,date,close',
'condition'=>'date=(SELECT MAX(date) FROM prices)'
)),
));
$this->render('index',array(
'prices'=>$prices
));
index.php:
<?php
$this->widget('bootstrap.widgets.TbGridView', array(
'dataProvider'=>$prices,
'template'=>"{items}",
'enablePagination' => false,
'columns'=>array(
array('name'=>'code', 'header'=>'Code'),
array('name'=>'name', 'header'=>'Name'),
array('name'=>'close', 'header'=>'Close'),
),
)); ?>
With this controller commands, I can get the data from table prices, but I can't get the data from table details.
Take a look at the with part of the criteria: http://www.yiiframework.com/doc/api/1.1/CDbCriteria#with-detail
I think your code should look something like this (untested):
$prices=new CActiveDataProvider('prices', array(
'criteria'=>new CDbCriteria (array(
'select'=>'code,date,close',
'with' => 'details',
'condition'=>'date=(SELECT MAX(date) FROM prices)'
)),
));
you already have reliation in Model. So do query like this in your controller
$prices=new CActiveDataProvider('prices', array(
'criteria'=>new CDbCriteria (array(
'condition'=>'date=(SELECT MAX(date) FROM prices)'
)),
));
In View just use
$data->code->name
$data->code->description
Here's what I change:
index.php
<?php
$this->widget('bootstrap.widgets.TbGridView', array(
'dataProvider'=>$prices,
'template'=>"{items}",
'enablePagination' => false,
'columns'=>array(
array('name'=>'code', 'header'=>'Code'),
array('name'=>'name', 'header'=>'Name', 'value'=>'$data->details->name'),
array('name'=>'close', 'header'=>'Close'),
),
)); ?>
Models Prices
public function relations(){
return array(
'details' => array(self::BELONGS_TO, 'Stocks_details', 'code'),
);
}