dongyang7152 2015-12-08 14:50
浏览 29

CakePHP如何从相关模型的另一个字段添加数据

This is one of my first applications out of tutorials so I don't know how to express my issue well.

Well I have these 2 tables:

User ( id, code )

Hours ( id, user_id, created)

I want to know how I can add an entry to the Hours table using the user_code.

I tried to grab the data of the User table with the code value and then findBy and pass for the patchEntity but it did not work.

  • 写回答

1条回答 默认 最新

  • douken0530 2015-12-09 15:27
    关注

    I don't have a whole lot of information to work with, but I'll give it a go.

    I want to know how I can add an entry to the Hours table using the user_code

    You mention using patchEntity, so that's updating information that's already there. Assuming user_code is the 'code' column you're talking about there, first find the user by his code:

    $users_tbl = TableRegistry::get('Users');
    // find the user
    $user = $users_tbl->findByCode($user_code)->first();
    
    if ($user) {
        // replace '$this->request->data() with whatever patch data you wanted
        $users_tbl->patchEntity($user, $this->request->data(), [
            'associated' => ['Hours']
        ]
    
        if ($users_tbl->save($user)) {
            // success!
        } else {
            // error!
        }
    } else {
        // error!
    }
    

    It will also depend on how you have the data you passed in (where my '$this->request->data() is, or whatever your array might be) - it needs to match the right column names and be in the correct format listed here.

    However, this is updating the data. Just adding the data, you can load the hours table and add a new entry with the user_id acquired from the user search:

    $hours_tbl = TableRegistry::get('Hours');
    $hours = $hours_tbl->newEntity([
        'user_id' => $user->id // $user populated from same method earlier
    ]);
    /* assumed 'id' was autoincrementing and 'created' was populated
       through Timestamp behavior */
    
    if ($hours_tbl->save($hours)) {
        // yay!
    } else {
        // boo
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)