当前位置:Gxlcms > PHP教程 > thinkphp关联模型多对多插入怎么使用?????

thinkphp关联模型多对多插入怎么使用?????

时间:2021-07-01 10:21:17 帮助过:1人阅读

  1. <code>$u = D('user');
  2. $u->name = 'xiak';
  3. $u->password = 'qqqqqq';
  4. $u->shop = array(
  5. 'gg' => '1',
  6. );
  7. $u->relation(true)->add($data);</code>
  1. <code>user(id, name)
  2. shop(id, name)
  3. user_shop(user_id,shop_id)</code>
  1. <code>class UserModel extends RelationModel {
  2. protected $_link = array(
  3. 'shop' => array(
  4. 'mapping_type' => self::MANY_TO_MANY,
  5. 'relation_table' => '__USER_SHOP__',
  6. )
  7. }</code>

怎么没有效果啊?

sql调试是这样的:

  1. <code>[user] SHOW COLUMNS FROM `tb_user` (executeTime: 0.009001s )
  2. [user] INSERT INTO `tb_user` (`name`,`password`) VALUES ('xiak','qqqqqq') (executeTime: 0.117007s )
  3. [shop] SHOW COLUMNS FROM `tb_shop` (executeTime: 0.013001s )
  4. [shop] INSERT INTO tb_user_shop (user_id,shop_id) SELECT a.id,b.id FROM tb_user AS a ,tb_shop AS b where a.id =45 AND b.id IN (1) (executeTime: 0.001000s )</code>

手册上说 当MANY_TO_MANY时,不建议使用关联插入。是什么意思啊?

回复内容:

  1. <code>$u = D('user');
  2. $u->name = 'xiak';
  3. $u->password = 'qqqqqq';
  4. $u->shop = array(
  5. 'gg' => '1',
  6. );
  7. $u->relation(true)->add($data);</code>
  1. <code>user(id, name)
  2. shop(id, name)
  3. user_shop(user_id,shop_id)</code>
  1. <code>class UserModel extends RelationModel {
  2. protected $_link = array(
  3. 'shop' => array(
  4. 'mapping_type' => self::MANY_TO_MANY,
  5. 'relation_table' => '__USER_SHOP__',
  6. )
  7. }</code>

怎么没有效果啊?

sql调试是这样的:

  1. <code>[user] SHOW COLUMNS FROM `tb_user` (executeTime: 0.009001s )
  2. [user] INSERT INTO `tb_user` (`name`,`password`) VALUES ('xiak','qqqqqq') (executeTime: 0.117007s )
  3. [shop] SHOW COLUMNS FROM `tb_shop` (executeTime: 0.013001s )
  4. [shop] INSERT INTO tb_user_shop (user_id,shop_id) SELECT a.id,b.id FROM tb_user AS a ,tb_shop AS b where a.id =45 AND b.id IN (1) (executeTime: 0.001000s )</code>

手册上说 当MANY_TO_MANY时,不建议使用关联插入。是什么意思啊?

难道就没有人跟我一样,觉得分拆SQL再加事务才是最好的方案吗,关联的SQL其它人看起来是不是很受罪呢

人气教程排行