add to a visual representation of a chart in a separate database

Having an issue with yii2 and in need of assistance: I have two databases, db1 and db2, both on MsSQL. In db2, there is a view linked to a table in db1. The problem arises when I try to insert into db2 as I am unable to retrieve the transaction id using $model->id or $model->getPrimaryKey(). Any solutions or suggestions on how to resolve this issue would be greatly appreciated. Below is my model:

<?php

namespace app\models;

use Yii;

class Documents extends \yii\db\ActiveRecord
{
    public static function primaryKey()
    {
        return ['id'];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'documents';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['realname', 'size'], 'required'],
            [['realname'], 'string'],
            [['size'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'realname' => 'Realname',
            'size' => 'Size',
        ];
    }


    /**
     * @return \yii\db\ActiveQuery
     */
    public function getDocumentSchoolRegistrationToInsurances()
    {
        return $this->hasMany(DocumentSchoolRegistrationToInsurance::className(), ['document' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getDocumentSchoolregistrations()
    {
        return $this->hasMany(DocumentSchoolregistration::className(), ['document' => 'id']);
    }

}

Answer №1

After thorough investigation and analyzing the yii2 source code, I have come to understand that when using save(), yii only reloads the registry values if the primary key is set to autoincrement, which is not the case for me.
In my situation, where it is a View, the workaround is to utilize Yii::$app->db->lastInsertID after calling the save() method in order to retrieve the id generated during the insert operation.
I believe it would be beneficial to have the ability to manually trigger a refresh of the newly created registry.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PHP incorporate diverse files from various subfolders located within the main directory

My question is similar to PHP include file strategy needed. I have the following folder structure: /root/pages.php /root/articles/pages.php /root/includes/include_files.php /root/img/images.jpg All pages in the "/root" and "/root/art ...

Update a scheduled task from invoking through a URL with cURL to invoking through the local command line using PHP

I currently have a cron file named cron.php. Within this file, I am implementing the curl_multi approach to initiate sub parallel tasks. For example, the crontab in cpanel will execute this script every minute: curl http://mywebsite.com/cron.php Within ...

The array that I am getting back is not being returned as an object

After making an AJAX request using a certain function, I noticed that the returned array is not in a valid format. It's quite different from what I'm used to in my AJAX experience. function get_within($latitude, $longitude) { global $pdo; // ...

Exploring the versatility of the ServiceLocatorInterface within a ZF2 Application

I am operating 2 different factories. The first one functions as a Controller Factory: <?php namespace Blog\Factory; use Blog\Controller\ListController; use Zend\ServiceManager\FactoryInterface; use Zend&b ...

A guide on efficiently incorporating a php variable into json format, then transferring it to ajax

My Sample Code var ajaxResponse = xmlhttp.responseText; //ajax response from my php file jsonData = JSON.parse(ajaxResponse); alert(jsonData.result); And in my PHP Script $resultValue = 'Hello'; echo '{ "result":"' . $result ...

Show the Best Deals on Category Pages Using Woocommerce

On my quest to showcase the lowest price on category pages instead of a price range, while still displaying the range on individual product pages, I stumbled upon a solution shared by another user: add_filter('woocommerce_variable_price_html', & ...

Determine unique dates from DateTime values in MySQL

I need to extract data from a database table that logs requests with an IP address column and a timestamp. My goal is to determine the number of days a specific IP address has made requests. I am currently using Laravel's query builder for this task. ...

Obtaining a specific section of text based on varying input values

Within a database, I have various requests that include the name of an image in the format of a .jpg file. The length of the image name can vary, so I am avoiding using substr() to extract it. An example value is "Added 545_4.jpg to Photo Album, The Briti ...

Retrieving JSON data from PHP using jQuery

I've been struggling with this issue for two whole days now, and I feel like I've hit a dead end in trying to solve it on my own. Here's the situation: I have two pages - one that contains a form with an address field that gets auto-filled ...

Difficulty organizing form inputs into arrays prior to submitting them through AJAX

I am currently developing a complex multi-step form that involves various sections such as Company, Job Site, Contact, and Product. My goal is to efficiently gather the form data either as an array or object before converting it into a string for transmiss ...

Using AJAX to submit a PHP form without refreshing the page

Currently, I am facing an issue with my PHP and AJAX code for posting data without redirecting the page. Surprisingly, the script works perfectly on the login page but not on other pages. The main difference I observed is that the login page uses if (empty ...

Flexible structure PHP API that supports requests and responses in JSON or XML format

I am currently in the process of developing a PHP API (web service) that will primarily involve retrieving lists of items. These items may have sub-objects with their own fields, or even nested objects. Since this API will be utilized by various projects, ...

What steps can I take to confirm that my cURL POST request is correctly executed in PHP?

I am faced with a challenge of handling a sample json object that contains specific data. My goal is to effectively store this information in a variable and then transmit it through a curl POST. $json = '{ "mac": "1234567890", "dns": "8.8.8.8 ...

Checking for a Match - Identifying if a string contains any characters from a different string

Is there a way to verify if a string contains any characters other than those listed below? A-Z 0-9 / \ - _ . ( ) space ...

Creating a new variable for every loop iteration in a foreach loop

I am attempting to create a for each loop that assigns a unique variable for each iteration of the array. Currently, when my loop runs, the variable $new only holds the final value, which is 17. Is there a way to make sure a different variable is assigned ...

Converting user's birthdate input from HTML to their age using PHP

I am facing an issue with retrieving the correct date from a date-time-picker named "dob" and passing it to PHP. When I try to post the date into the database user_age column, it only displays '2017'. However, if I manually set $dob to '10/0 ...

Although the ajax call returned a 404 Not Found error, the functionality of the code still

$(".click").click(function(){ var request = $.ajax({ type: "POST", url: "post.php", data: {file: "123"} }); }); Despite encountering a "404 Not Found" error in Firebug when running this code with the po ...

Custom Link Condenser... Hyperlink Rewriter

Currently, I am faced with some challenges while attempting to develop a straightforward URL shortener: A) Wondering about the possibility of rewriting mydomain.com in the .htaccess file, specifically aiming to enable users to input mydomain.com/4854 whil ...

Utilizing Jquery for precise element placement and retrieving its position details

Within my bundle of jQuery code, there are a few areas where I am experiencing difficulties trying to recall functions. The following is an excerpt of the code: $(document).ready(function(){ $("#myTablePager").html(""); $.ajax({ type: "POS ...

What's the best way to set up automatic deletion on a timed schedule?

My current framework is codeigniter As an example, I have a table called A. Is it possible for my system to automatically delete all records in table A every 2 minutes? Any insights on achieving this would be greatly appreciated ...