YII2 creating relations in models between tables from 2 databases - yii2

I have defined 2 databases , for example
return [
'components' => [
'db1' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=db1name',
'username' => 'db1username',
'password' => 'db1password',
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=db2name',
'username' => 'db2username',
'password' => 'db2password',
],
],
];
Now i have a table as 'users' in 'db1' and table 'countries' in 'db2'
users
id , country_code , username , password
1 , DE , xyz , 12345
2 , FR , abc , 12345
countries
code , name
DE , Germany
FR , France
IN , India
I have defined the foreign key relation between users.country_code & countries.code
ISSUE
But when i try to create the model for 'users' table using gii it gives an error , possibly because the tables relation are from 2 different databases.
How to use tables from different databases in relations of a model.
Any suggestions are welcomed

This works in my case to list iten on GridView::widget
-> bd_sisarc is my secound data base
-> deposito_sondagem is a table from my first data base
public static function getDb() // on your model
{
return Yii::$app->get('db1');
}
public static function getDb() // on your model
{
return Yii::$app->get('db2');
}
public function getEmpresaSondagem() // Relation on you model
{
return $this->hasOne(EmpresaSondagem::className(), ['idEmpSondagem' => 'entidade_deposito']);
}
public function search($params)
{
$this->load($params);
$sql = "SELECT deposito_sondagem.*
FROM
deposito_sondagem,
`bd_sisarc`.`tbempresasondagem`
WHERE
`bd_sisarc`.`tbempresasondagem`.`idEmpSondagem`=`deposito_sondagem`.`entidade_deposito`
and deposito_sondagem.estado=1
and tbempresasondagem.estado=1
and numero_registo LIKE '%$this->numero_registo%'
and nomeempsondagem LIKE '%$this->nomeEntidade%'
and dono_sondagem LIKE '%$this->dono_sondagem%'
and data_deposito LIKE '%$this->data_deposito%'";
$query = DepositoSondagem::findBySql($sql);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
return $dataProvider;
}

Try this one
SELECT `users`.* FROM `users` LEFT JOIN `db2name`.`countries` ON `users`.`country_code` = `db2name`.`countries`.`code `

Related

How to have relationship in Laravel 5.7 based on a json data key saved in a table column?

I am using this Staudenmein package in Laravel and referring to this answer given by the package owner himself.
I have two tables, pets and notifications with models Pet and Notification.
The notifications table has a column called data which is of JSON dataType and stores JSON data
{"pet_id":"4","pet_type_id":1,"lost_report_id":3,"pet_sighting_id":21,"latitude":"22.676846","longitude":"88.338509"}
The key pet_id denotes the id column of the pets table. I need a relationship so that I can fetch the name of the pet from pets table.
By referring to the answer link given above, I wrote my Notification model like this:-
namespace App\Models;
use DB, App, Auth, Hash, Lang, Mail, Config, Exception, Validator, Globals;
use Illuminate\Database\Eloquent\Model;
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
use App\User;
use App\Models\AdminConfig;
use App\Models\ReceivedAppNotification;
class Notification extends Model
{
protected $casts = [
'data' => 'json'
];
public function notificationPet()
{
return $this->belongsTo('App\Models\Pet', 'data->pet_id');
}
}
When I am running the query like this:-
$notificationQuery = Notification::with('notificationPet')
->whereRaw("FIND_IN_SET('$userId', in_app_notification_receiver)")
->where(array(
'status' => Globals::SMALL_CHAR_ACTIVE,
'is_delete' => Globals::SMALL_CHAR_NO,
))->get()->toArray();
I get the notificationPet relationship as empty, ie. the data-set is like this:-
Array
(
[id] => 10
[title] =>
[message] =>
[data] => Array
(
[pet_id] => 4
[latitude] => 22.676846
[longitude] => 88.338509
[pet_type_id] => 1
[lost_report_id] => 3
[pet_sighting_id] => 34
)
[no_of_in_app_notification_receiver] => 2
[no_of_push_notification_receiver] => 1
[from_user] => 22
[in_app_notification_receiver] => 2,23
[push_notification_receiver] => 2
[status] => a
[is_delete] => n
[push_notification_sent] => n
[created_date] => 2020-03-19 13:23:17
[modified_date] => 2020-03-19 13:23:17
[created_at] => 2020-03-19 13:23:17
[updated_at] => 2020-03-19 13:23:17
[notification_pet] =>
)
However, I have a record in pets table with id = 4, already. So the relationship should not be empty.
What am I doing wrong?
Change:
protected $casts = [
'data' => 'json'
];
To:
protected $casts = [
'data' => 'array'
];

An Issue with saving SalesOrders data from REST API call to Exact Online

I have been using PHP Client library for Exact Online for a long time.
After saving the customer Accounts, Addresses, Contacts and then filtering out the PaymentConditions based on WooCommerce orders, items are successfully reflecting in the Exact Online dashboard.
But unfortunately calling the SalesOrders post request API. I'm unable to store into the Exact Online dashboard,
even though in order to store only OrderedBy itself is enough which is given in the official documentation
$ordersn = $order->save();
Picqer\Financials\Exact\ApiException : Error 403: Forbidden
$order = new SalesOrder($connection);
$lines = new SalesOrderLine($connection);
....
echo'<pre>'; print_r($order);
$order->SalesOrderLines = $lines;
$ordersn = $order->save();
if ($ordersn->ID)
{
$orderitem['sync_flag'] = true;
}
Here is the details of an order array
Picqer\Financials\Exact\SalesOrder Object
(
...
[attributes:protected] => Array
(
[WarehouseID] => 26ca2016-453f-499a-8a34-c986009bc78d
[OrderID] => FC290B7D-766B-4CBB-B7A2-47327AA3841F
[OrderedBy] => 764a4f6d-4b39-43b4-a86c-265e5478afbd
[DeliverTo] => 764a4f6d-4b39-43b4-a86c-265e5478afbd
[OrderDate] => 2019-02-17T19:29:53
[YourRef] => 75591901YP220320G
[OrderedByName] => Peter Kerner
[Description] => 16031_PayPal/Lastschrift/Kreditkarte
[Remarks] => Order is processing
[PaymentReference] => 16031
[PaymentCondition] =>
[SalesOrderLines] => Picqer\Financials\Exact\SalesOrderLine Object
(
[attributes:protected] => Array
(
[OrderID] => FC290B7D-766B-4CBB-B7A2-47327AA3841F
[VATAmount] => 5,58
[Description] => Goodies Box
[Quantity] => 1,00
[UnitPrice] => 29,37
[Item] => 418d43d6-55fe-410a-8df2-b05cbb72cea5
)
...
)
)
...
)
Do we need to upload VAT code or Am I missing something else data to be resided first shown from the above order-array or what else should we need to call appropriate API. Since in-order to reflect on the Exact Online dashboard. what should we need to follow?
From the built-In function call addItem() below snippets of code:
$soLines = array(
'OrderID' => $lines->OrderID,
'Item' => $lines->Item,
'Description' => $lines->Description,
'Quantity' => $lines->Quantity,
'UnitPrice' => $lines->UnitPrice,
'VATAmount' => $lines->VATAmount,
'VATCode' => $lines->VATCode
);
$order->addItem($soLines);
Generates the results with LineNumber to be included in SalesOrderLines array
[attributes:protected] => Array
(
[WarehouseID] => 26ca2016-453f-499a-8a34-c986009bc78d
[OrderID] => 65F93F56-97A8-4D54-AE37-C0BDDE774E67
[OrderedBy] => 9b048b81-f729-413a-b196-526436f11fe7
[DeliverTo] => 9b048b81-f729-413a-b196-526436f11fe7
[OrderDate] => 2019-02-17T20:45:34
[YourRef] => 9Y9593859V795183K
[OrderedByName] => Katrin Lenk
[Description] => 16033_PayPal Express
[Remarks] => Order is processing
[PaymentReference] => 16033
[PaymentCondition] =>
[SalesOrderLines] => Array
(
[0] => Array
(
[OrderID] => 65F93F56-97A8-4D54-AE37-C0BDDE774E67
[Item] => 5c415369-615c-4953-b28c-c7688f61cfaa
[Description] => ABC Classic
[Quantity] => 2,00
[UnitPrice] => 15,08
[VATAmount] => 5,73
[VATCode] =>
[LineNumber] => 1
)
)
)
Also note I haven't created Journals, GLAccounts, Documents & DocumentAttachments API. Does this actually affects storing of SalesOrders
EDIT:
In much simpler
$salesOrder = new \Picqer\Financials\Exact\SalesOrder($connection);
$salesOrder->WarehouseID = '26ca2016-453f-499a-8a34-c986009bc78d';
$salesOrder->OrderID = '65F93F56-97A8-4D54-AE37-C0BDDE774E67';
$salesOrder->OrderedBy = '9b048b81-f729-413a-b196-526436f11fe7';
$salesOrder->DeliverTo = '9b048b81-f729-413a-b196-526436f11fe7';
$salesOrder->OrderDate = '2019-02-17T20:45:34';
$salesOrder->YourRef = '9Y9593859V795183K';
$salesOrder->OrderedByName = 'Katrin Lenk';
$salesOrder->Description = '16033_PayPal Express';
$salesOrder->Remarks = 'Order is processing';
$salesOrder->PaymentReference = '16033';
$salesOrder->PaymentCondition = 'PP';
$soLines = array(
'Item' => '5c415369-615c-4953-b28c-c7688f61cfaa',
'Description' => 'ABC Classic',
'Quantity' => '1,00',
'UnitPrice' => '29,37',
'OrderID' => '65F93F56-97A8-4D54-AE37-C0BDDE774E67'
);
echo '<pre>'; print_r($soLines);
$salesOrder->addItem($soLines);
echo '<pre>'; print_r($salesOrder);
$salesOrder->save();
Resulting value stored from the soLines array
[attributes:protected] => Array
(
[WarehouseID] => 26ca2016-453f-499a-8a34-c986009bc78d
[OrderID] => 65F93F56-97A8-4D54-AE37-C0BDDE774E67
[OrderedBy] => 9b048b81-f729-413a-b196-526436f11fe7
[DeliverTo] => 9b048b81-f729-413a-b196-526436f11fe7
[OrderDate] => 2019-02-17T20:45:34
[YourRef] => 9Y9593859V795183K
[OrderedByName] => Katrin Lenk
[Description] => 16033_PayPal Express
[Remarks] => Order is processing
[PaymentReference] => 16033
[PaymentCondition] =>
[SalesOrderLines] => Array
(
[0] => Array
(
[OrderID] => 65F93F56-97A8-4D54-AE37-C0BDDE774E67
[Item] => 5c415369-615c-4953-b28c-c7688f61cfaa
[Description] => ABC Classic
[Quantity] => 2,00
[UnitPrice] => 15,08
[VATAmount] => 5,73
[VATCode] =>
[LineNumber] => 1
)
)
)
Actual Result:
Picqer\Financials\Exact\ApiException : Error 403: Forbidden
The reason was OrderID value was included twice in the SalesOrderLine as well as in SalesOrder for the two REST API calls and removing the OrderID entry from SalesOrder worked perfectly and reflecting in the Exact Online Dashboard
You cannot assign $order->SalesOrderLines = $lines; directly resulting in a collection to array error.
The only way to do this was to call via in-built function called addItem() passing array objects into it.

Cakephp3 multiple join table by Model

I have problem with my code. At this moment I have code view like this:
...Table.php
public function containBasic(){
return [
//Keywords
'CandidatesKeywords',
'CandidatesKeywords.Keywords',
//User
'CandidatesUser',
'CandidatesUser.User',
];
}
...Controller.php
$this->loadModel('Candidates');
$candidates = $this->Candidates->find()
->contain($this->Candidates->containBasic())
->where([
'CandidatesKeywords.Keywords.id'=>5
])
->all();
I include all other Models via contain. This method its works but when I try to search data in this code I have error like:
Unknown column 'CandidatesKeyword.id' in 'where clause
I don't know, how I can get column CandidatesKeywords -> Keywords -> Id from database :/
When I get (debug) all rows without where condition I get data like this:
'items' => [
(int) 0 => object(Cake\ORM\Entity) {
'id' => (int) 4,
.........
,
'candidates_user' => null,
'candidates_keyword' => object(App\Model\Entity\CandidatesKeyword) {
'id' => (int) 1,
..................
'keyword' => object(App\Model\Entity\Keyword) {
'id' => (int) 5,
.............
And I need to get rows with only keyword.id = 5.

How to join three tables and get value in grid view

I have three tables :
contacts hasMany groups
contact_groups hasMany contacts
contact_contact_groups
columns in table contact
contact_id | contact_name
columns in table contact_groups
group_id | group_name
columns in table contact_contact_groups
contact_contact_group_id | contact_id | group_id
MODEL
contacs model
public function getContactContactGroups()
{
return $this->hasMany(ContactContactGroups::className(),
['contact_id' => 'contact_id']);
}
contact_groups model
public function getContactContactGroups()
{
return $this->hasMany(ContactContactGroups::className(),
['group_id' => 'group_id']);
}
contact_contact_groups model
public function getGroup()
{
return $this->hasOne(ContactGroups::className(), ['group_id' => 'group_id']);
}
public function getContact()
{
return $this->hasOne(Contacts::className(), ['contact_id' => 'contact_id']);
}
I want to display grid like this :
-----------------------------
Contact Name | Group Name
-----------------------------
Me | Uncategorized
Mother | Family
Jhon | Business
VIEW
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'tableOptions' =>['class' => 'table table-striped table-bordered'],
'columns' => [
[
'attribute' => 'contact_name',
'value' => 'contact_name',
],
[
'attribute' => 'contactContactGroups.group_id',
'value' => 'contactContactGroups.group.group_name',
'filter' => Html::activeDropDownList($searchModel, 'group_id', ArrayHelper::map(ContactGroups::find()->where(['group_status'=>'ACTIVE'])->asArray()->all(), 'group_id', 'group_name'),['class'=>'form-control','prompt' => 'Select Group']),
],
],]);
?>
ContactsController
public function actionIndex() {
$this->unsetThisButton(array(4,5));
$searchModel = new ContactsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
But it showing (not set) not a group_name .
A simple way is based on adding a getter in your model eg: for contact_contact_groups model
you have a relation
public function getGroup()
{
return $this->hasOne(ContactGroups::className(), ['group_id' => 'group_id']);
}
use a getter for group_name
public function getGroup_group_name() {
return $this->group->group_name;
}
and in grid view in the attribute
[
'attribute' => 'group_group_name',
'filter' => Html::activeDropDownList($searchModel, 'group_id', ArrayHelper::map(ContactGroups::find()->where(['group_status'=>'ACTIVE'])->asArray()->all(), 'group_id', 'group_name'),['class'=>'form-control','prompt' => 'Select Group']),
],
do the same for the relation and field
I Found simple stuff like this :)
GRID (VIEW)
[
'attribute' => 'contactContactGroups.group_id',
'value'=>function ($data) {
$d = array();
foreach ($data->contactContactGroups as $k=>$m)
{
$d[] = ContactContactGroups::get_group_name_by_id($m->group_id);
}
return implode($d, ', ');
},
'filter' => Html::activeDropDownList($searchModel, 'group_id', ArrayHelper::map(ContactGroups::find()->where(['group_status'=>'ACTIVE'])->asArray()->all(), 'group_id', 'group_name'),['class'=>'form-control','prompt' => 'Select Group']),
],
models/ContactContactGroups.php Model
I create function get_group_name_by_id($id)
public static function get_group_name_by_id($id){
$model = ContactGroups::find()->where(["group_id" => $id])->one();
if(!empty($model)){
return $model->group_name;
}
return null;
}
so the result is :
Contact | Category
-------------------------------
Me | Business, Family
Erick | Business, Office
Jhon | Office
Thank's #scaisEdge, you give me some clue ;)

DB Query in Drupal 7

I am trying to run a db query in drupal where, the content type has a node association field, and I am trying to get all notes of that type, where the NID of the current node matches any of the nodes specified in said note association field.
a visual example
Nodetype1
-- Node Association Field
NodeType2
I would like to get all Nodetype1's where Node Association Field matches the NID of Nodetype2 that is currently loaded.
My current db query is like so:
db_query("SELECT * FROM field_data_field_promo_profile WHERE field_promo_profile_nid=".$N->nid);
and this returns nothing, when i know for a fact that such a node exists, I also tried dropping the WHERE statement and it returns an array like this:
DatabaseStatementBase Object ( [dbh] => DatabaseConnection_mysql Object ( [shutdownRegistered:protected] => [target:protected] => default [key:protected] => default [logger:protected] => [transactionLayers:protected] => Array ( ) [driverClasses:protected] => Array ( [SelectQuery] => SelectQuery [DatabaseSchema] => DatabaseSchema_mysql [MergeQuery] => MergeQuery [DatabaseTransaction] => DatabaseTransaction [UpdateQuery] => UpdateQuery [InsertQuery] => InsertQuery_mysql ) [statementClass:protected] => DatabaseStatementBase [transactionSupport:protected] => 1 [transactionalDDLSupport:protected] => [temporaryNameIndex:protected] => 0 [connectionOptions:protected] => Array ( [database] => cityhound_dev [username] => blahblah [password] => blahblah [host] => localhost [port] => [driver] => mysql [prefix] => Array ( [default] => ) ) [schema:protected] => DatabaseSchema_mysql Object ( [connection:protected] => DatabaseConnection_mysql Object *RECURSION* [placeholder:protected] => 0 [defaultSchema:protected] => public [uniqueIdentifier:protected] => 4fd7fba9e563e2.50177866 ) [prefixes:protected] => Array ( [default] => ) [prefixSearch:protected] => Array ( [0] => { [1] => } ) [prefixReplace:protected] => Array ( [0] => [1] => ) ) [queryString] => SELECT * FROM field_data_field_promo_profile )
Any one have some ideas ?
db_query() returns an iterable object, so you just need to iterate over it:
$result = db_query("SELECT * FROM field_data_field_promo_profile WHERE field_promo_profile_nid=".$N->nid);
foreach ($result as $row) {
$entity_id = $row->entity_id;
// etc...
}
You should use parameters in your queries to prevent SQL injections.
For instance the query above should look like this:
$result = db_query("SELECT * FROM {field_data_field_promo_profile} p
WHERE p.field_promo_profile_nid = :nid ", array(':nid' => $N->nid);
foreach ( $result as $row ) {
$entity_id = $row->entity_id;
// etc...
}