change someone else's code

I took over the backend of the Yii2 mall for secondary development given by a boss, and then the backend of the subsequent projects were changed based on this backend;

But you should understand that different projects, the data returned by the interface required by the front end, and the project database structure are very different;

Then, today I encountered a front-end requirement: the interface needs to return the category name to which the product belongs.

ok, isn't it simple, when the product information interface returns data, the product table and the category table are jointly queried (relying on the category ID) to return the category name of the product by the way

$list = $query->leftJoin(['gp' => $pic_query], 'gp.goods_id=g.id')
            ->leftJoin(['gn' => $od_query], 'gn.goods_id=g.id')
            ->leftJoin(['c' => Cat::tableName()], 'c.id=g.cat_id')
            ->select('g.id,g.name,g.cat_id,c.name,g.service,g.price,g.cover_pic pic_url,gn.num,g.virtual_sales,g.unit')
            ->limit($pagination->limit)
            ->offset($pagination->offset)
            ->asArray()->all();

The red letter is added by me, pay attention to this c.name, the goods table has a field named name (commodity name), and the cat table also has a field named name (category name), and then look at the data returned by the front-end interface;

There is only one name attribute, and it is the value of the name field of the cat table in the data table. Needless to say, this is overwriting g.name;

ok, then I change the name field of the category table (cat) to cname , and then query it, but after doing this, the nightmare begins;

All the controllers, models, and views related to the cat table will report errors. I searched them one by one. There are currently 9 php files associated with them (there may be others in the future? . . )

model:CatListForm.php--GoodListForm.php--CatForm.php--Cat.php

controller:GoodsController.php

view:cat.php--goods.php--good-edit.php--cat-edit.php

After the modification, everything is now functioning normally.

In addition, don't forget to change the name field name of the database cat to cname.

After this, sum up a lesson, it can be considered to benefit others and self. When building a table, it is best to make the field names between each table easy to distinguish, such as the name field for students and the name field for teachers;

It is best to write them as sname and tname respectively. On the one hand, it is semantic, and on the other hand, it avoids unnecessary troubles in the future.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324894687&siteId=291194637