Coder Social home page Coder Social logo

mootensai / yii2-relation-trait Goto Github PK

View Code? Open in Web Editor NEW
46.0 10.0 44.0 115 KB

Yii 2 Models add functionality for load with relation, & transactional save with relation PLUS soft delete/restore feature

PHP 100.00%
relational model softdelete yii2 yii2-extension relational-databases relational-model

yii2-relation-trait's People

Contributors

bitdeli-chef avatar cgernert avatar cronfy avatar dibyanshu11 avatar markux avatar mootensai avatar mzglinski avatar scrutinizer-auto-fixer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-relation-trait's Issues

Can't save hasMany relation without index 0 (zero)

As mentioned in the description of the extension, the hasMany relation array must have numerical keys:

            // has many
            [relationName] => Array 
                ( 
                    [0] => Array 
                        (
                            [relAttr] => relValue1
                        )
                    [1] => Array 
                        (
                            [relAttr] => relValue1
                        )
                )

And in the code we can see that the key 0 is required in deleteWithRelated and restoreWithRelated methods, that calls something like:
$error = !$this->{$data['name']}[0]->updateAll($this->_rt_softdelete, ['and', $array]);

I have an relation with alphanumeric keys, which doesn't have a numerical index and gives a index not defined error.
In order to solve it, I made a change to access the array data like the following:

array_values($this->{$data['name']})[0]

This approach is only valid to PHP 5.4+ though.

Composite Primary Key

Hi
I try to use relation trait for this table:

CREATE TABLE test (
table1id bigint(20) NOT NULL,
table2id bigint(20) NOT NULL,
field1 tinyint(4) DEFAULT NULL,
PRIMARY KEY (table1id,table2id),
KEY key1_id_fk (table1id),
CONSTRAINT key1_id_fk FOREIGN KEY (table1id) REFERENCES table1 (id),
CONSTRAINT key2_id_fk FOREIGN KEY (table2id) REFERENCES table2 (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

as you can see I'm trying to use a composite primary key without an "id" column. I don't know if this is an issue, since if I change the name of my 'table1id' column into 'id' everything works fine. My problem is, that I have to change all my database schema (not only one column ;-) ) and before doing that I preferred asking you if there is a way to fix that.

saveAll() on update with unique constraint fails

When saveAll() is trying to save multiple records with delete + update/insert, it first saves new/updated models and then deletes remaining models.

But if there is database constraint, it can prevent save operation, regardless that database would be consistent after all (save + delete) operations are finished.

It would not occur if saveAll() would firstly delete removed models and save other models then.

Below is a detailed example. Consider these models:

/*
SQL:

 CREATE TABLE `product` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255),
  PRIMARY KEY (`id`)
)
*/
class Product extends ActiveRecord {

    use RelationTrait;

    public function getProductToProductCategories() {
        return $this->hasMany(ProductToProductCategory::class, ['product_id' => 'id']);
    }
}

/*
SQL:

CREATE TABLE `product_to_product_category` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) NOT NULL,
  `product_category_id` int(11) NOT NULL,
  `is_main` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `product_id-is_main` (`product_id`,`is_main`) # IMPORTANT
)
*/
class ProductToProductCategory extends ActiveRecord {
}

A product can have multiple category links. One of product categories can be main category of the product.

Important part is unique key on product_id + is_main. There can not be more than one product_id with is_main set to 1 (multiple NULLs are allowed).

We have these rows in product_to_product_category (step-1):

+------+------------+---------------------+---------+
| id   | product_id | product_category_id | is_main |
+------+------------+---------------------+---------+
| 1677 |       2703 |                   4 |    NULL |
| 1689 |       2703 |                   6 |       1 |
| 1693 |       2703 |                  16 |    NULL |
+------+------------+---------------------+---------+

We want this (step-2):

+------+------------+---------------------+---------+
| id   | product_id | product_category_id | is_main |
+------+------------+---------------------+---------+
| 1677 |       2703 |                   4 |       1 |
+------+------------+---------------------+---------+

To achieve this, at step-1 we remove models 1689, 1693 (thanks to wbraganca/yii2-dynamicform!) and set is_main = 1 to 1677, then call saveAll().

It firstly trying to save 1677, 2703, 4, 1 and MySQL rejects with 1062 Duplicate entry '2703-1' for key 'product_id-is_main', because 1689, 2703, 6, 1 is still there.

If saveAll() would firstly delete removed models and saved the rest, everything would be ok.

Issue if there is more than one realtion in one table

Hi mootensai

don't know if you remember me? We talked about some issues some time ago and you fixed them all, except one. The title of this thread should explain everything, so, if I have more than one relation in my table, updating fails, because you don't "reset" the $fields array for every relation. The problem only occures if the related tables have different names of their key columns. I fixed that bug in my local version by adding this to line 104 in your RelationTrait.php file:
$fields = [];
Could you please verify that and eventually add it too, so I don't have to edit the file manually after your updates.

Thanks for the great work!

SaveAll() function Deletes Related Records unexpectedly.

The Saveall() function will delete related records if those relations were not completely found by LoadAll() or were not fully presented on the CRUD view.

Example ....

  • "Owner" -has many- "Cars" -has many- "Parts"
  • CRUD form has sub forms for "Cars" and "Parts"

If there are several hundred "parts" for one "car" and several "cars" for each "owner", then the list of "Parts" records on the CRUD can run into hundreds or thousands of records. The List of "Parts" on the CRUD view can / will be incomplete.

If a new "car" is added or the "owner" record is then saved, the missing "parts" records from the CRUD view will be deleted from the database.

In an extreme case, if you LoadAll(), including "Parts" , but do not display the "Parts" records in the CRUD view, then SaveAll() will delete EVERY "parts" record.

This is probably the same problem that occured in this bug report #67

Problem with several many-to-many relations

I've some issue with this module.
Sorry for my English :(
My project has several model with many-to-many relations. For example one model has 2 many-to-many relation. With this model RelationTrait throw exception:
PHP Notice: Undefined index 'blah-blah'.

I disable E_NOTICE in php.ini but Yii2 throw MySQL PDO exceptions.
I investigate this problem and I found this solution to solve this problem.

I glad to reply any questions.
RelationTrait.zip

This extension is pure shit and should be deleted !!!

This extension rape through all methods prefixed with "get" and abuse them. This method clears link table records and creates new - effectively messing in more complex relations. This is pure VIRUS and the author should be ashamed!

AR Method afterSave() of related model will be marked as deleted

Hi Guys,

I use this great extension for different projects, thanks a lot!!!

In my case, I would like to write the history of changes in Company Name in a has-many table calles Company Names. For this I use the following method in the company model:

public function afterSave($insert, $changedAttributes) {

    // init superclass
    parent::afterSave($insert, $changedAttributes);
    
    if(!$insert && isset($changedAttributes['name'])) {
        // your code here like $changedAttributes['myField'];
        
        $modelCompanyName = new \app\models\CompanyName();
        
        $modelCompanyName->tbl_company_id = $this->id;
        
        $modelCompanyName->name = $this->name;
        
        $modelCompanyName->valid_from = date('Y-m-d H:i:s');
                
        $modelCompanyName->save();
    }         
}	

Unfortunately, if I save the company with changed name field, the data will be saved in company name table correctly, but will be marked (I use softdelete) as deleted.

I suggest that afterSave is executed after saving the company model, the relation trait will deal after with the related models and use the information of the request, which haven't that information.

One solution will be to use saveAll method with parameters (['companyName']) to avoid saving this information, but if some of the names should be deleted this information will be ignored.

Can I change the order how relation trait save the models or is there any other turnaround?

Thanks a lot!

Tobi

Clean your code from debug messages

There must not be any debug messages in a "library" . you sholud remove all echo, var_dump, etc. You can use Yii::trace() , which will make your messages appear in the yii 2 debug bar

Multiple n:m in one form

Hello mootensai

I unfortunately think I found another mistake. In the attached example I have 4 tables: main (the main table), sub1 (first n:m relation), sub2 (second n:m relation), persons (the target table of the n:m relations).
All the models, controller and views I created with IO Generator of gii and leaved them untouched.

Now if you try to go the main view in yii2 everything works fine, as long as I put in values for only one subquery. At the moment I try to put in values for subquery1 and subquery2 it fails with this error message:

SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 3 column(s)
The SQL being executed was: DELETE FROM sub2 WHERE (mainid=1) AND ((mainid, personsid, somevalue) NOT IN (('1','1'), ('1','2'), ('1','3'), ('1','2','23')))
example.sql.zip

What do you mean with "What function do you use?"? The error occures when put values in both subForms an try to save the main form. As said before, it works perfectly as long as I leave one of the subForms empty.

File uploading problem in related models

Hi,

I 've two model. The first model(Subject) has two fields: id, title and the second model(Files) has three fields: id, subject_id, file_name.
After submitting I see this validation message: "Files #1: Please upload a file.", but I Select a file to upload. I set form enctype field to 'multipart/form-data'.
Is there any solution to solve this problem?
thanks

oracle case sensitive column name

currently

foreach ($link as $key => $value) { if (isset($this->$value)) { $array[$key] = "$key = '{$this->$value}'"; } }

suggestion

foreach ($link as $key => $value) { if (isset($this->$value)) { $array[$key] = "\"$key\" = '{$this->$value}'"; } }

Too few arguments to function app\models\base\Dokter::getListDokterRS(), 0 passed and exactly 1 expected

Hi mootensai, i had problem when update the date. The error is quite strange.

in C:\xampp\htdocs\mcs3x\models\base\Dokter.php at line 126

    'updatedByAttribute' => 'updated_by',
        ],
      ];
}

public function getListDokterRS($rs_id)
{
    $data = Yii::$app->db->createCommand(
        'SELECT t_dokter.nama_dokter, t_dokter.kode_dokter
            FROM t_dokter_poli
            INNER JOIN t_dokter ON t_dokter_poli.kode_dokter = t_dokter.kode_dokter
            WHERE kode_poli in (SELECT kode_poli from t_poli WHERE kode_rs = :kode_rs)')
        ->bindValue(':kode_rs', $rs_id)
        ->queryAll();
  1. app\models\base\Dokter::getListDokterRS()

  2. in C:\xampp\htdocs\mcs3x\vendor\mootensai\yii2-relation-trait\RelationTrait.php at line 417 –
    call_user_func([app\models\Dokter, 'getListDokterRS'])

                         continue;
             }
             if (strpos($method->name, 'get') !== 0) {
                 continue;
             }
             try {
                 $rel = call_user_func(array($this, $method->name));
                 if ($rel instanceof ActiveQuery) {
                     $name = lcfirst(preg_replace('/^get/', '', $method->name));
                     $stack[$name]['name'] = lcfirst(preg_replace('/^get/', '', $method->name));
                     $stack[$name]['method'] = $method->name;
                     $stack[$name]['ismultiple'] = $rel->multiple;
                     $stack[$name]['modelClass'] = $rel->modelClass;
    
  3. in C:\xampp\htdocs\mcs3x\vendor\mootensai\yii2-relation-trait\RelationTrait.php at line 43 – app\models\base\Dokter::getRelationData()

Feature Request: softDelete()

Unless I'm using this trait incorrectly, to use soft deletes we need to always use the method $model->deleteWithRelated(). The method $model->delete() continues to do a hard delete. While I like that $model->deleteWithRelated() recurses through children data to soft delete them as well as the parent, sometimes it would be nice to simply have a softDelete() instead of building an exception list for $skippedRelations.

Is that on the drawing board? Would you accept a PR with this method if not?

Relation records empty after main entity insert

Hi I have an issue on trying to create record. Then I found what on

public function saveAll($skippedRelations = [])
{
    /* @var $this ActiveRecord */
    $db = $this->getDb();
    $trans = $db->beginTransaction();
    $isNewRecord = $this->isNewRecord;
    try {
        if ($this->save()) {
            $error = false;
            if (!empty($this->relatedRecords)) {
  • relatedRecords - is empty if main entity inserting, on update everything OK. Sorry my eng. pls

The object being updated is outdated.

Hi,

I've built a crud app with mootensai/yii2-enhanced-gii, there are related tables by foreign keys (n:1, n:m).

In the case I got an validation error, after pressing update a second time the app throw the following error:

`Stale Object Exception – yii\db\StaleObjectException
The object being updated is outdated.

1. in /home/none/work/rebase/vendor/yiisoft/yii2/db/BaseActiveRecord.php at line 813
804805806807808809810811812813814815816817818819820821822

                            if ($lock !== null) {
            $values[$lock] = $this->$lock + 1;
            $condition[$lock] = $this->$lock;
        }
        // We do not check the return value of updateAll() because it's possible
        // that the UPDATE statement doesn't change anything and thus returns 0.
        $rows = static::updateAll($values, $condition);
 
        if ($lock !== null && !$rows) {
            throw new StaleObjectException('The object being updated is outdated.');
        }
 
        if (isset($values[$lock])) {
            $this->$lock = $values[$lock];
        }
 
        $changedAttributes = [];
        foreach ($values as $name => $value) {
            $changedAttributes[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
                

2. in /home/none/work/rebase/vendor/yiisoft/yii2/db/ActiveRecord.php at line 631 – yii\db\BaseActiveRecord::updateInternal(null)
3. in /home/none/work/rebase/vendor/yiisoft/yii2/db/BaseActiveRecord.php at line 681 – yii\db\ActiveRecord::update(true, null)
4. in /home/none/work/rebase/vendor/mootensai/yii2-relation-trait/RelationTrait.php at line 166 – yii\db\BaseActiveRecord::save()
160161162163164165166167168169170171172

                            /* @var $this ActiveRecord */
        $db = $this->getDb();
        $trans = $db->beginTransaction();
        $isNewRecord = $this->isNewRecord;
        $isSoftDelete = isset($this->_rt_softdelete);
        try {
            if ($this->save()) {
                $error = false;
                if (!empty($this->relatedRecords)) {
                    /* @var $records ActiveRecord | ActiveRecord[] */
                    foreach ($this->relatedRecords as $name => $records) {
                        if (in_array($name, $skippedRelations))
                            continue;
                

5. in /home/none/work/rebase/controllers/SalesLeadController.php at line 145 – app\models\base\SalesLead::saveAll()

`

anybody an idea what's the problem?

Cheers!

Multiple m:n fields in one form

Hi again 😄

it seems to me, that there is an issue if we use more then one m:n fields in the same form.

if (!$relSave || !empty($relModel->errors)) {
$relModelWords =
Inflector::camel2words(StringHelper::basename($AQ->modelClass));
$index++;
foreach ($relModel->errors as $validation) {
foreach ($validation as $errorMsg) {
$this->addError($name, "$relModelWords #$index : $errorMsg");
}
}
$error = true;
} else {
//GET PK OF REL MODEL
if ($isManyMany) {
foreach ($relModel->primaryKey as $attr => $value) {
$notDeletedPK[$i][$attr] = "'$value'";
$fields[$attr] = "";

The problem is the $fields[$attr] Array. You never free it when a new relation is called and so all the attributes of the "old" relation remain also attributes of the new relation, even if they do not exist. I fixed this by setting $fields = [] at the beginning (in my case line 95 of your code).
Now I'm able to save new data with more than one m:n relations, but deleting of items doesn't work anymore, if the items list is empty (works if there is at least one item left). What do you think?

deleteWithRelated only works with direct relations

The method deleteWithRelated() only seems to work with direct relations.

So this works just fine:

parent -> child

If I $parent->deleteWithRelated() then both parent and child are soft deleted.

However, this fails:

parent -> child -> child_of_child

In this situation, only parent and child are soft deleted, while child_of_child is untouched.

The solution is to update yii2-relation-trait with the needed information:

class parent()...
{
    public function relationNames()
    {
        return [
            'child',
            'child_of_child',
        ];
    }
    
    public function getChildOfChilds()
    {
        return $this->hasMany(ChildOfChild::className(), ['child_id' => 'id'])->via('Childs');
    }
}

However, if I remove relationNames() in the class def and let deleteWithRelated real-time determine this, it doesn't soft delete child_of_child. (

)

Is this correct behaviour?

Yii2-dynamic forms - Nested Dynamic Form

Firstly thank you for this extension and sorry for my bad english!

I'm using this extension with Yii2-dynamicforms and it works perfecly on simple scenario, avoiding unnecessary code.

Now I'm trying to use with Nested Dynamic Form example and i'm getting this error:

error_relation

This occurs when I create a relation via a junction table in Person model.

public function getHouses()
{
     return $this->hasMany(House::className(), ['person_id' => 'id']);
}
public function getRooms()
{
     return $this->hasMany(Room::className(), ['id' => 'person_id'])->via('houses');
}

Is there any solution to this problem or the extension does not support it?

Thank you!

Using Enhanced Yii2 Gii - no relation

Hi,

I have simple table in database:

CREATE TABLE Document
(
DocumentID INTEGER NULL,
Title VARCHAR(50),
Published DATE
);

ALTER TABLE Document ADD PRIMARY KEY (DocumentID);

I created model and CRUD, but when I try to create new Document I'm getting error:
Invalid Parameter – yii\base\InvalidParamException
app\models\Document has no relation named "published-document-published".
Caused by: Unknown Method – yii\base\UnknownMethodException
Calling unknown method: app\models\Document::getpublished-document-published()

Please help me, I'm getting this error only when I have Date field in database.

$this->relatedRecords is empty

Hi,
I'm trying to retrieve releted data with $model->getAttributesWithRelated() but the result is empty.
In the method there is a
foreach ($this->relatedRecords as $name => $records) {
but I don't find where relatedRecords is set....

I'm calling getAttributesWithRelated() on a model retrieved by a find()->one()

little bug?

in function "deleteWithRelated()" $array has to be reseted...

so the original code is:

 public function deleteWithRelated()
    {
        /* @var $this ActiveRecord */
        $db = $this->getDb();
        $trans = $db->beginTransaction();
        try {
            $error = false;
            $relData = $this->getRelationData();
            foreach ($relData as $data) {
                if ($data['ismultiple']) {
                    $link = $data['link'];
                    if (count($this->{$data['name']})) {
                        $relPKAttr = $this->{$data['name']}[0]->primaryKey();
//                        $isCompositePK = (count($relPKAttr) > 1); // unused
                        foreach ($link as $key => $value) {
                            if (isset($this->$value)) {
                                $array[$key] = "$key = '{$this->$value}'";
                            }
                        }
                        $error = !$this->{$data['name']}[0]->deleteAll(implode(' AND ', $array));
                    }
                }
            }
....

And here the corrected one...

public function deleteWithRelated()
    {
        /* @var $this ActiveRecord */
        $db = $this->getDb();
        $trans = $db->beginTransaction();
        try {
            $error = false;
            $relData = $this->getRelationData();
            foreach ($relData as $data) {
//-----
// Missing this line??               
                $array = array();
//---- 
                if ($data['ismultiple']) {
                    $link = $data['link'];
                    if (count($this->{$data['name']})) {
                        $relPKAttr = $this->{$data['name']}[0]->primaryKey();
//                        $isCompositePK = (count($relPKAttr) > 1); // unused
                        foreach ($link as $key => $value) {
                            if (isset($this->$value)) {
                                $array[$key] = "$key = '{$this->$value}'";
                            }
                        }
                        $error = !$this->{$data['name']}[0]->deleteAll(implode(' AND ', $array));
                    }
                }
            }

Thanks for your great work!

Has Many Relation - delete items

Hi,

I use yii2-relation-trait with genreated CRUD by Gii (with your yii2-enhanced-gii)
I have Has Many relation. For example orders and order items.

So: I have saved Order with one or more order items.
If there is at least one order item. It works fine. If not, relation save is skipped.It looks like saveAll function gets full relatedRecors to this relation. So code in if (!empty($this->relatedRecords)) { is processed

Marek

Filtered record being deleted on update

Type 🐛

class Company () {
    ...
    public function getBranches()
    {
        return $this->hasMany(\common\models\Branch::className(), ['company_id' => 'id'])
        ->andWhere(['type' =< 10 ]);
    }
}

on update company record, those record with type 11 and above got deleted...

Suggestion :
add $ignoreClause parameter for saveAll() as additional

    public function saveAll($skippedRelations = [],$ignoreClause = [])
    {
        ....
        $query = ['and', $notDeletedFK, ['not in', $relPKAttr[0], $notDeletedPK]];
        array_push($query, $ignoreClause);           ....
        ...
        if (!empty($notDeletedPK)) {
            try {
                if ($isSoftDelete) {
                    $relModel->updateAll($this->_rt_softdelete, $query);
                } else {
                    $relModel->deleteAll($query);
                }
            } catch (IntegrityException $exc) {
                $this->addError($name, "Data can't be deleted because it's still used by another data.");
                $error = true;
            }
        }
        ....
    }

or adding list of effectiveIds only

Error : Too few arguments to function app\models\base\Penilaian::getPenilaianDetsWithParam(), 0 passed and exactly 1 expected

I have created a manual method for filtering relation data. But relation trait not supported this method with a parameter or how to send the parameter to this new method? Thank you.

public function getPenilaianDetsWithParam($kinerjaId)
    {
        return $this->hasMany(\app\models\PenilaianDet::className(), ['penilaian_id' => 'id'])->where('kinerja_id = :kinerjaId', [':kinerjaId' => $kinerjaId])
            ->orderBy('kinerja_id');
    }

Wrong bracket

Hi.

Great job, man! I saved a lot of time with this trait

I has some problem with one-to-one relatios and found small bug. Check please:

ELSE statement for one-to-one relation (line202) belong to wrong IF. Now it's for if (!empty($records))(127)
but should be for if ($AQ->multiple)(132)

Way to fix:

  • move closing bracket from line 200 to line 217

getRelationData conflicts with user defined methods

First of all, you are doing a great job. Keep up the good work.

I have a problem with methods I add to model classes. getRelationData calls all the methods in a model and it conflicts with those I add.

Looks like you added a try-catch with no statement "//if method name can't be call" to prevent issues, but if a user-defined method throws an exception, it stops the execution where you don't expect it to stop.

You need to find a way to skip user defined methods without an attempt to call them. User methods may doing exhaustive calculations or db calls. Your method makes unnecessary calls.

Maybe one way would be to let developers to start their methods with certain way, like adding 'my' or 'user', etc., in the front.

Another way would be to let people add methods to their models while getRelationData only looks for methods in its base class or a parent class.

I will solve this temporarily by checking a prefix of mine, which will be a problem in the next update.

Thanks.

update failed with no relation

i use your gii generator, when i use the update function i got some error like in this picture
image
can u help me what wrong with the code

ID column for Related model doesn't populate on Post

I'm using loadAll() function and works fine, but It doesn't populate the id for the related model

{ "id":"6", "idEscolaridade":"16", "descricao":"teste", "salario":5500.00, "Escolaridades":{ "id":"16", "descricao":"testando" } }

I'm using 'jaacoder/yii2-activated' to mapping the attributes, works for the parent model, but doesn't work for related models (ID column only)

My mapping function on "Escolaridades" model :
`

public static function mapping(){
  return [
       'id' => 'esco_id',
      'descricao' => 'esco_descricao'
   ];

}
`

record deleted immediately after insert

My model is saved, but immediately deleted.

The condition for the DELETE seems to be a value in a column that is NOT a relationship (FK) column.

Thoughts?

yii2-dynamicform - Delete Relation

What treatment do I use when all relations are removed from Dynamic Form?

Whenever I remove all items from Dynamic Form, it returns again, and I see in the database the primary ID of the related table, it remains the same.

Using Enhanced Yii2 Gii CRUD with skipped relations

(sory for my poor english)

Hi,
dont know if its bug, or just I dont get it right.

I generate model and CRUD files with mootensai/yii2-enhanced-gii. In gii CRUD form I skip some relations. Then after update form submit all related rows are deleted. Controller dint get skipped relation data in POST and saveAll delete all related rows (RelationTrait:197)

My scenario:
I create some orders with client "asdasd", then I go to client update (generated with skipeed relations: orders) and confirm form. All orders for client "asdasd" will be deleted.

Is that right or I miss something?

Thanks for answer

sql:
`SET NAMES utf8;
SET time_zone = '+00:00';
SET foreign_key_checks = 0;
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';

DROP TABLE IF EXISTS client;
CREATE TABLE client (
id int(11) NOT NULL AUTO_INCREMENT,
client_group_id int(11) DEFAULT NULL,
type enum('retail','wholesale') NOT NULL,
payment_method enum('cache','transfer') NOT NULL,
name varchar(128) NOT NULL,
description text,
address varchar(128) DEFAULT NULL,
phone varchar(128) DEFAULT NULL,
email varchar(128) DEFAULT NULL,
PRIMARY KEY (id),
KEY client_group_id (client_group_id),
CONSTRAINT client_ibfk_3 FOREIGN KEY (client_group_id) REFERENCES client_group (id) ON DELETE SET NULL ON UPDATE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO client (id, client_group_id, type, payment_method, name, description, address, phone, email) VALUES
(14, 19, 'retail', 'cache', 'asdasd', '', '', '', ''),
(15, 19, 'wholesale', 'cache', 'test 2', '', '', '', '');

DROP TABLE IF EXISTS client_group;
CREATE TABLE client_group (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(128) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO client_group (id, name) VALUES
(19, 'Cenik pro frajera');

DROP TABLE IF EXISTS order;
CREATE TABLE order (
id int(11) NOT NULL AUTO_INCREMENT,
client_id int(11) DEFAULT NULL,
order_status_id int(11) DEFAULT NULL,
date_created datetime DEFAULT NULL,
date_ordered datetime DEFAULT NULL,
date_to_deliver datetime DEFAULT NULL,
date_shipped datetime DEFAULT NULL,
date_completed datetime DEFAULT NULL,
date_tax datetime DEFAULT NULL,
price_total decimal(10,2) DEFAULT NULL,
PRIMARY KEY (id),
KEY client_id (client_id),
KEY order_status_id (order_status_id),
CONSTRAINT order_ibfk_3 FOREIGN KEY (order_status_id) REFERENCES order_status (id),
CONSTRAINT order_ibfk_4 FOREIGN KEY (client_id) REFERENCES client (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS order_status;
CREATE TABLE order_status (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(128) NOT NULL,
color varchar(32) DEFAULT NULL,
paid tinyint(1) NOT NULL DEFAULT '0',
shipped tinyint(1) NOT NULL DEFAULT '0',
delivered tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO order_status (id, name, color, paid, shipped, delivered) VALUES
(1, 'New', 'red', 0, 0, 0),
(3, 'Delivered', '', 0, 0, 0);

-- 2016-04-21 17:31:29`

deleteWithRelated not working

While we use deleteWithRelated() for deleting relational data using viaTable. Yii2-relation-trait, deliver exception.
Does this module support (ViaTable) Relations or not?

after validation on new related, return model with id

Hi,

I 've a simple main form, with a tabular form: I add two new rows: Document 1 not valid and Document 2 valid.

After submit I see the correct validation message "Document #1 : Percentage cannot be blank. ", BUT Document 2 has an id value setted! Then after new submit I got an exception on RelationTrait line 71, because $relObj is null ( $relModelClass::findOne($relPost[$relPKAttr[0]]); return null because id is setted, but it not exist on db)

thanks

Deletion of has many relation works wrong

  • add new first has-many relation to entity (with empty id)
  • save all relations
  • add new second has-many relation and delete first (with empty id)
  • save all relations
  • first relation won't be deleted

Few bugs

First thanks for your nice work.
Out team found and fix few bugs in your code, maybe you can update repo:

At line 329 we changed:

            if (strpos($method->name, 'get') === false) {
                continue;
            }
            try {
                $rel = call_user_func(array($this, $method->name));
                if ($rel instanceof \yii\db\ActiveQuery) {
                    $name = lcfirst(str_replace('get', '', $method->name));
                    $stack[$name]['name'] = lcfirst(str_replace('get', '', $method->name));

with this code:

          if (strpos($method->name, 'get') !== 0) {
               continue;
           }
           try {
               $rel = call_user_func(array($this, $method->name));
               if ($rel instanceof \yii\db\ActiveQuery) {
                   $name = lcfirst(preg_replace('/^get/', '', $method->name));
                   $stack[$name]['name'] = lcfirst(preg_replace('/^get/', '', $method->name));

that checks only for methods that starts with 'get' and replace just first occurence of that word
avoiding replace of getProgetto() in Protto().

At line 66 we added after:
$relObj = (empty($relPost[$relPKAttr[0]])) ? new $relModelClass : $relModelClass::findOne($relPost[$relPKAttr[0]]);

this:

if (is_null($relObj)) {
     $relObj = new $relModelClass();
}

avoiding null ref

Thanks again for your work and see u soon

Not respecting skippedRelations property

On line 124 in RelationTrait.php file you have probably an error, i think that you shoud check skippedRelations before that if, because now if something shoud be skipped it is treated as hasOne relation because of if/else statement.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.