![](/img/trans.png)
[英]Grabbing user id of current logged user and add it as foreign key value in a different table returns null - MySQL - CodeIgniter
[英]Assigning current user_id as foreign value in a different table
我有以下表格用戶(ID,名稱,電子郵件),文章(ID,user_id,標題,正文)。 我似乎無法用登錄的user_id填充articles表中的user_id。 這是我的代碼。
//文章控制器
public function add() {
if ($this->request->is('post')) {
$this->Article->create();
$this->request->data['Article']['user_id'] = $user_id;
if ($this->Article->save($this->request->data)) {
$this->Session->setFlash(__('The article has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The article could not be saved. Please, try again.'));
}
}
$users = $this->Article->User->find('list');
$this->set(compact('users'));
}
上面的方法為文章中的user_id返回空值
我也嘗試從視圖中檢索:
echo $this->Form->hidden('user_id', arrray('value' => $userAuth['id']));
我收到以下錯誤語法錯誤,意外的'=>'(T_DOUBLE_ARROW)
echo $this->Form->hidden('user_id', arrray('value' => $userAuth['id']));
應該,
echo $this->Form->hidden('user_id', array('value' => $userAuth['id']));
錯別字(R的3倍)。
嘗試這個:
public function add() {
if ($this->request->is('post')) {
$this->Article->create();
if ($this->Article->save($this->request->data)) {
$this->Session->setFlash(__('The article has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The article could not be saved. Please, try again.'));
}
else{
$this->set('user_id', $userAuth['id']);
$users = $this->Article->User->find('list');
$this->set(compact('users'));
}
}
在視圖中
echo $this->Form->hidden('Article.user_id', arrray('value' => $user_id));
但是我不知道您在哪里設置$userAuth
,請確保在獲取變量值之前分配該變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.