开发者

cakephp HABTM database upload cant find issue

I am new to cakePHP and fairly new to PHP as well, I have gone through some Youtube videos to help me make a basic site set up with CRUD pages for everything. I am now trying to set up the user signup page to add a bunch of stuff to a HABTM table but cant figure out what is going wrong.

$this->User->create();
        if ($this->User->save($this->data)) {
            $lvl = $this->data['User']['level'];
            $charids = $this->Kanji->find('list',array('conditions'=>array('grade' <= $lvl,'grade' >= 0)));
            foreach ($charids as $charid){
                $characterList = array('kanji_id'=>$charid,'user_id'=>$this->User->id, 'level'=>2);

                $this->kanjisUsers->save($characterList);

A bit of clarification, The site is for a school project, I want it to help with learning Japanese and the idea is that you can put a 开发者_开发知识库string of Japanese text and it will simplify it to your level so when you sign up you tell it what your level of Japanese is (an int between 1 and 9) then it will go through the character list (kanjis table) and find all with a number equal to or less than your level (called 'grade' in the kanjis table) then I want it to add all these to the kanjis_users table with the int 2 to indicate it is known (then I will do it again with one level up characters and save them with int 1 for 'learning') I had help with the code and am not sure how it all works, I have been changing lots of things and cant figure out what is wrong, any suggestions?

note: I also saw that the model was called kanjis_user.php and KanjisUser, I read the model should not be plural but when I tried to change it everything crashed, could this be a part of the problem? I have also tried changing => with -> and vice versa and also created $characterList to remove it from the save function, don't know if these affected anything as it never worked...

Edit in response to comment by api55:

Here is the model relation For kanjis_users:

class KanjisUser extends AppModel {
    var $name = 'KanjisUser';
//Validation stuff here
var $belongsTo = array(
        'Kanji' => array(
            'className' => 'Kanji',
            'foreignKey' => 'kanji_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

Here is the kanji mode:

var $hasAndBelongsToMany = array(
    'User' => array(
        'className' => 'User',
        'joinTable' => 'kanjis_users',
        'foreignKey' => 'kanji_id',
        'associationForeignKey' => 'user_id',
        'unique' => true,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'finderQuery' => '',
        'deleteQuery' => '',
        'insertQuery' => ''
    )
);

Here is the user model:

var $hasAndBelongsToMany = array(
    'Kanji' => array(
        'className' => 'Kanji',
        'joinTable' => 'kanjis_users',
        'foreignKey' => 'user_id',
        'associationForeignKey' => 'kanji_id',
        'unique' => true,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'finderQuery' => '',
        'deleteQuery' => '',
        'insertQuery' => ''
    ),

This is just the standard generated model (minus validation).

For clarification on the error, there is no error, it just doesn't work, It saves the user, but dose not add anything to the kanjis_users table. Here is the whole register controller as it is now:

function register() {
    if (!empty($this->data)) {


        $this->User->create();
        if ($this->User->save($this->data)) {
            $lvl = $this->data['User']['level'];
            //$test = $this->Kanji->find ('list',array('Kanji.grade <='<=$lvl, 'AND'=>array('Kanji.grade >=' >= 1)));
            $charids = $this->Kanji->find('list',array('conditions'=>array('grade <=' => $lvl,'grade >=' >= 1)));
            //print_r($charids);
            //exit();
            //$this->kanjisUsers->save(array('kanji_id'=>$charids,'user_id'=>$this->User->id));
            //$this->kanjisUsers->saveALL(array('kanji_id'=>$charids,'user_id'=>$this->User->id));
            foreach ($charids as $charid){
                //echo("<p>Charid: ".$charid." is: </p>");
                //var_dump($charid);
                $this->kanjisUsers->save(array('kanji_id'=>$charid,'user_id'=>$this->User->id),'level'=> 2);
            }

        //exit();

        $this->Session->setFlash(__('The user has been saved', true));
        $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
        }
    }

}

Both seem to generate a similar array, but however I change the code sometimes it will crash, sometimes it will save the user, but it will never do anything to the kanjis_users table.

What I want:(simplified for clarity:

User table has: name, username, pw, userID etc... kanjis table has: a Chinese character per row with ID, English, grade(int from 0 to 9) etc... kanjis_users has: ID, user_id, kanji_id, created(date), modified(date), level(int).

I want a user to put a level when they sign up and then when the user gets created it will populate the kanjis_users table with all the rows in the Kanji table that have a 'grade' between 1 and the level the user put in the sign up form (called 'level').

So what I am trying to do above is after the user is saved (this user create() at the top), I then test if the save was a success and then get the level the user put in the form, and try to get all the characters from the rows from the kanjis table where the level is equal to or less than that (note I don't want to get ones with 0 as they are the hardest ones...) and add them all to the kanjis_users table. (this is only for sign up, when using the system the user can add and remove characters as they wish)

I noticed with the print_r that it was getting all 12000~ rows from the kanjis table, so I think the filter was not working...

I hope this makes sense, please let me know if I need to put any further info.


Create an input box in the register view:

$this->Form->input('Kanji', array('type' => 'hidden'));

Then try this:

function register() {
if (!empty($this->data)) {
    $this->User->create();
    $lvl = $this->data['User']['level'];
    $charids = $this->Kanji->find('list',array('conditions'=>array('grade <=' => $lvl,'grade >=' => 1)));
    $i = 0;
    foreach ($charids as $charid){
        $this->data['Kanji']['Kanji'][$i] = $charid;
        $i++;
    }
    if ($this->User->save($this->data)) {
        $this->Session->setFlash(__('The user has been saved', true));
        $this->redirect(array('action' => 'index'));
    } else {
        $this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
    }
}

}

How it works

  1. You save current level to $lvl ($this->data['User']['level'];)
  2. You find all Kanjis maching your criteria ($charids = $this->Kanji->find('list',array('conditions'=>array('grade <=' => $lvl,'grade >=' => 1)));)
  3. You define a new variable equal 0 ($i = 0;)
  4. You make a loop going through your data array, storing every Kanjis you found and assigning it to $this->data['Kanji']['Kanji'] as it would be default data if you have selected it in a form.
  5. You save the data as it has been filled by a form.


Ok, I see wrong 2 things :D

1) You get 12000+ rows from the find beacause your find condition is wrong :S and the one commented that i gave you has typos

the find MUST BE like this:

$test = $this->Kanji->find ('list',array(
      'conditions'=> array(
          'Kanji.grade <=' => $lvl,
          'AND' => array(
              'Kanji.grade >=' => 1)
           )
       )
);

2) the data in your save is wrong:

The cookbook explains that the data passed needs to be like this :

Array
(
    [ModelName] => Array
        (
            [fieldname1] => 'value'
            [fieldname2] => 'value'
        )
)

So your save part should look something like this:

$this->KanjiUser->create();
$data = array(
         'KanjiUser' => array(
                 'KanjiUser.kanji_id'=>$charid,
                 'KanjiUser.user_id'=>$this->User->id,
                 'KanjiUser.level'=>2
          )
);
if ($this->KanjiUser->save($data))
   echo 'Done ;)';
else
   echo 'error';

all this inside the foreach or you can do the saveAll approach

$data = array('KanjiUsers'=> array());
foreach ($charids as $charid){
                $data ['KanjiUsers'][] = array(
                    'KanjiUser' => array(
                         'KanjiUser.kanji_id'=>$charid,
                         'KanjiUser.user_id'=>$this->User->id,
                         'KanjiUser.level'=>2
                     )
                );
}
$this->KanjiUser->create();

if ($this->KanjiUser->saveAll($data['KanjiUser'))
   echo 'Done ;)';
else
   echo 'error';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜