Jump to content

How to correctly send data to multiple tables in Codeigniter


Kirasiris

Recommended Posts

So I've been struggling with this for quite a while now and is already my last step to get done with my project(finally). The main problem is that I'm trying to create a many-to-many relationship between three tables that I have on my database.

 

I'm attaching the table that I'm using on this post (ci_terms, ci_terms_taxonomy, ci_terms_relationship).

 

So far the main code works great(the one for adding the post, which I will post the whole code after explaining what I'm trying to do). When adding a post everything works as I want except when I try to select the categories(not the selection itself); instead of submiting ONLY the SELECTED values, all values are being submitted even those which are not selected.

 

Here are some pictures to clarify what I mean:

 

45.jpg

46.jpg

 

 

then in the post appear all three(or more depending on the number of categories that I have created).

 

47.jpg

 

I hope I could make myself clear.

Thanks in advance.

 

Here is the code that I'm using for the many-to-many relationship tables:

<?php            
// Create many-to-many relationship /////////////////////////////
            $taxonomy_list = $this->Terms_model->get_list();

            foreach ( $taxonomy_list as $cat ){
                //do insert here
                $data = array(
                    'term_taxonomy_id'  => $this->db->insert_id(),
                    'term_id'           => $cat->term_id,
                    'type'              => 'category',
                    );
            }

            $this->Taxonomy_model->add($data);

            $data = array();

            $relationship_list = $this->Taxonomy_model->get_list();

            foreach ( $relationship_list as $rel ){
                // Insert selected values
                $data[] = array(
                    'post_id'           => $last_post_id,
                    'term_taxonomy_id'  => $rel->term_taxonomy_id,
                    'term_order'        => 0,
                    );
            }

            $this->db->insert_batch('ci_terms_relationship', $data);
?>

and here is the full code I'm using for the addition of new posts(with the code above also):

<?php
    public function add()
    {
        // Field Rules
        $this->form_validation->set_rules('title', 'Title', 'trim|required|min_length[3]');
        $this->form_validation->set_rules('body', 'Body', 'trim|required');
        $this->form_validation->set_rules('status', 'Status', 'required');
        $this->form_validation->set_rules('is_featured', 'Feature', 'required');
		$this->form_validation->set_rules('is_commented', 'Comments', 'required');
        $this->form_validation->set_rules('order', 'Order', 'integer');


        if ($this->form_validation->run() == FALSE) {
							
			// Select Categories	
			$categories_options = array();
			$categories_options[0] = 'Select Categories';
			
			$categories_list = $this->Terms_model->get_list();
			
			foreach($categories_list as $cat){
				$categories_options[$cat->term_id] = $cat->title;
			}
			
			$data['categories_options'] = $categories_options;
			
			// Select Post Author ID and Name
			$user_options = array();
			$user_options[0] = 'Select Username ID';
			
			$user_list = $this->User_model->get_list();
			
			foreach($user_list as $username){
				$user_options[$username->id] = $username->username;
			}
			
			$data['user_options'] = $user_options;
			
            // Load template
            $this->template->load('admin', 'default', 'posts/add', $data);
        } else {
            $slug = str_replace(' ', '-', $this->input->post('title'));
            $slug = strtolower($slug);
			
			// Upload Image
			$config['upload_path'] = 'assets/img/posts/';
			$config['allowed_types'] = 'gif|jpg|png';
			$config['encrypt_name'] = TRUE;
			$config['max_size'] = '2048';
			$config['max_width'] = '2000';
			$config['max_height'] = '2000';
			$this->load->library('upload', $config);
			$this->upload->initialize($config);
					
			
			$file_name = 'post_image';
			
			if(!$this->upload->do_upload($file_name)){
				varDebug($this->upload->display_errors());
				$file_name = 'assets/img/noimage.jpg';
			} else {
				$post_image =  $this->upload->data('file_name');
			}
			
			// Page Data
            $data = array(
				'user_id'		=> $this->input->post('user_id'),
				'slug'			=> $slug,
				'title'			=> $this->input->post('title'),
				'post_image'	=> $post_image,
				'body'			=> $this->input->post('body'),
				'status'		=> $this->input->post('status'),
				'is_featured'	=> $this->input->post('is_featured'),
				'is_commented'	=> $this->input->post('is_commented'),
				'order'			=> $this->input->post('order'),
				'type'			=> 'post',
            );
			
            $this->Post_model->add($data);

            // Get last post id for inserting of categories data
            $last_post_id = $this->db->insert_id();

            // Get title for activity data
            $activity_title = $data['title'];

            // Create many-to-many relationship /////////////////////////////
            $taxonomy_list = $this->Terms_model->get_list();

            foreach ( $taxonomy_list as $cat ){
                //do insert here
                $data = array(
                    'term_taxonomy_id'  => $this->db->insert_id(),
                    'term_id'           => $cat->term_id,
                    'type'              => 'category',
                    );
            }

            $this->Taxonomy_model->add($data);

            $data = array();

            $relationship_list = $this->Taxonomy_model->get_list();

            foreach ( $relationship_list as $rel ){
                // Insert selected values
                $data[] = array(
                    'post_id'           => $last_post_id,
                    'term_taxonomy_id'  => $rel->term_taxonomy_id,
                    'term_order'        => 0,
                    );
            }

            $this->db->insert_batch('ci_terms_relationship', $data);

            ///////////////////////////////////////////



            // Activity Array
            $data = array(
                'resource_id' => $last_post_id,
                'type'        => 'post',
                'action'      => 'added',
                'user_id'     => $this->session->userdata('user_id'),
                'message'     => 'A new post was added (' . $activity_title . ')'
            );

            // Insert Activity
            $this->Activity_model->add($data);

            // Set Message
            $this->session->set_flashdata('success', 'Post has been added');

            // Redirect
            redirect('admin/posts');
        }
    }
?>

Again, thanks, I really need help with this.

post-202668-0-89089100-1524637488_thumb.jpg

post-202668-0-90705500-1524637494_thumb.jpg

post-202668-0-67689200-1524637499_thumb.jpg

Link to comment
Share on other sites

I'm sorry if did not explain myself clearly enough. What I want is to find a correct way to create a many-to-many relationship table as I'm building a CMS similar to WordPress(in fact I have those three tables exactly as the ones WordPress uses).

 

I'm trying to build a simple blog system in which I need to display all the categories related to any single post and when clicking on them(on the categories) being able to redirect the user to a page displaying all the post which contain that specific category(the "clicked" one).. I don't know if I explained it better but in few words I'm just building a blog system exactly like WordPress.

 

I already tried looking for tutorials, I tried doing pure php(obviously with my own data):

$array = array(
    "foo" => "bar",
    42    => 24,
    "multi" => array(
         "dimensional" => array(
             "array" => "foo"
         )
    )
);

var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);

I just don't find a right answer for it. I mean I could easily do a one-to-many relationship table but that;s not exactly what I want... if you sir have a good idea about what I can do,  I will greatly appreciate it.

 

Thanks in advance.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.