Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

rscarpim

Relacionamento 2 Tabelas ?

Recommended Posts

Pessoal a duvida e a seguinte:

Tenho a Tabela mae : tb_doc_document

Tenho a Tabela Filho : tb_doc_category

Gostaria de saber como criar uma VIEW para Trazer os Dados da tabela mae, juntamente com os respectivos Registros Filhos Exemplo:

Title = bla bla bla cat_description = categoria um

Title = bla bla bla cat_description = categoria dois

Title = bla bla bla bla cat_description = categoria tres

Title = bla bla bla bla cat_description = categoria tres

Title = bla bla bla cat_description = categoria quatro

Title = bla bla bla cat_description = categoria quatro

Title = bla bla bla cat_description = categoria quatro

Preciso exibir isto em uma Table e estou usando Ajax mais nao estou sabendo muito como lidar com a ideia, se alguem tiver um exemplo de como colocar o Titulo da categoria como Divisor entre as tabelas e depois a tabela com a descricao.

Obrigado pessoal um grande abraco

Compartilhar este post


Link para o post
Compartilhar em outros sites

Boa Tarde. Você precisa vincular alguma informação a eles, como por exemplo um id:

Nome Colunas da tabela

tabela1: id, title, descricao_id

tabela2: id, descricao

como ficaria o select:

SELECT tabela1.id as ID, tabela1.title as Titulo, tabela2.descricao as Descricao FROM tabela1

JOIN tabela2

ON tabela1.descricao_id = tabela2.id

Compartilhar este post


Link para o post
Compartilhar em outros sites

Muitissimo Obrigado meu amigo pela resposta, mais eu ja tenho a vinculacao:

Tabela Mae:

CREATE TABLE `tb_doc_document` (
	`doc_id` INT(11) NOT NULL AUTO_INCREMENT,
	`doc_title` VARCHAR(255) NULL DEFAULT '0',
	`doc_description` LONGTEXT NULL,
	`doc_date_created` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
	`doc_priority` SMALLINT(6) NULL DEFAULT NULL,
	`doc_filepath` LONGTEXT NULL,
	`doc_category_id` INT(11) NULL DEFAULT NULL,
	`doc_company_id` INT(11) NULL DEFAULT '0',
	PRIMARY KEY (`doc_id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=4

Tabela Filha:

CREATE TABLE `tb_doc_category` (
	`cat_id` INT(11) NOT NULL AUTO_INCREMENT,
	`cat_description` VARCHAR(255) NOT NULL DEFAULT '0',
	`cat_company_id` INT(11) NULL DEFAULT NULL,
	PRIMARY KEY (`cat_id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=3
;

Esta e a View que uso para o Relacionamento.

select `d`.`doc_id` AS `doc_id`,
`d`.`doc_title` AS `doc_title`,
`d`.`doc_description` AS `doc_description`,
`d`.`doc_company_id` AS `doc_company_id`,

`c`.`cat_description` AS `cat_description` 

from (`tb_doc_document` `d` left join `tb_doc_category` `c` on((`c`.`cat_id` = `d`.`doc_category_id`)))

E Este e o meu Ajax para a Criacao das tabelas :

    /*  Name            : FListDocuments
    *   Objective       : Bring the List of Categories to the Screen Administrator Format.
    *   Date Created    : 12/19/2016
    *   Date Edited     :
    *   Parameters      :
    *       @pTypeSearch   : This Parameter show's the information based on the type, Example:
                1   = Full, show all content on the Table in Administrator Mode.
                2   = Make the Search Based on the Button Explore Documents. 
    *   Autor           : Ricardo Scarpim.
    */ 
    function FListDocuments(pTypeSearch){


        var vSearch     = '';
        
        var vFields     = new Array();

        var vField      = '';


        /* Creating the SQL Based on the pTypsSearch*/
        switch(pTypeSearch)
        {

            /* Regular Search no Criteria. */
            case 1:

                vSearch     = 'pTpSearch=1&pSQL=SELECT DISTINCT * FROM tb_doc_category WHERE cat_company_id = "' + vCompany  + '" ORDER BY cat_description';

                break;

            /* Search with Bind Parameters, that means Search with some Criteria. */
            case 2: 


                vSearch     = 'pTpSearch=1&pSQL=SELECT DISTINCT * FROM v_doc_document WHERE cat_description = ' + '"' + $('#txtSearch').val() + '"'  + ' AND doc_company_id = "' + vCompany + '" GROUP BY cat_description ASC ORDER BY cat_description';
               
                break;

            /* When using the Search Field make the Query Criteria with %*/
            case 3:

                vSearch     = 'pTpSearch=1&pSQL=SELECT DISTINCT * FROM tb_doc_category WHERE cat_description LIKE "' + $('#txtSearch').val() +'%" GROUP BY cat_description ASC ORDER BY cat_description';
                
                break;

            case 4:

                var vArrTyped   = new Array( $('#txtSearch').val() );

                var vArrFields  = new Array( 'doc_title', 'doc_description', 'cat_description')

                vSearch     = 'pTpSearch=2';


                break;
        }

       
        
        /* Searching the DataBase. */   
        $.ajax({
            
            url         : 'DBSearch.php',
            data        : vSearch,
            type        : 'post',
            async       : false,
            dataType    : 'json',
          
            
            success: function (dt) { 

                if(dt.length > 0 && dt !== null)
                {
                    
                    var vHtml       = '';

                    $.each(dt, function (k){

                        vHtml += '<div class="row" id="div-cat-' + dt[k].cat_id +'">';

                            vHtml += '<div class="col s12 m12 l12" style="background-color:#e0e0e0;border-radius: 5px;">';

                                vHtml += '<h4>' + dt[k].cat_description + '</h4>';
                            vHtml += '</div>';


                            $.ajax({
                                
                                url         : 'DBSearch.php',
                                data        : 'pTpSearch=1&pSQL=SELECT DISTINCT * FROM v_doc_document WHERE cat_description = "' + dt[k].cat_description + '"' ,
                                type        : 'post',
                                async       : false,
                                dataType    : 'json',

                                success: function(dts){

                                    if(dts.length > 0 && dts !== null)
                                    {

                                        vHtml += '<div class="col s12 m12 l12">';

                                            vHtml += '<table class="responsive-table highlight" id="tblData" data-id="'+ dt[k].cat_id +'">';

                                                vHtml += '<thead>';

                                                    vHtml += '<th></th>'
                                                    vHtml += '<th data-field="title"                    style="width:30%;">Title</th>';
                                                    vHtml += '<th data-field="description"              style="width:40%;">Description</th>';
                                                    vHtml += '<th data-field="type" class="right-align" style="width:10%;">Type</th>';
                                                    vHtml += '<th data-field="edit"                     style="width:10%;"></th>';
                                                    vHtml += '<th data-field="delete"                   style="width:10%;"></th>';
                                                vHtml += '</thead>';

                                                vHtml += '<tbody>';

                                                    var vExt        = '';
                                                    var vFileExt    = '';

                                                    /* All Database Result. */
                                                    $.each(dts, function (j){

                                                        vExt     = dts[j].doc_filepath;
                                                        
                                                        vExt !== null ?  vFileExt = vExt.substring(vExt.lastIndexOf('.') + 1): vFileExt = '';

                                                        vHtml += '<tr>';

                                                            vHtml += '<td></td>';
                                                            dts[j].doc_filepath         !== null    || dts[j].doc_filepath      !== undefined ? vHtml += '<td><a href="'+ dts[j].doc_filepath +'" target="_blank">' + dts[j].doc_title + '</a></td>': vHtml += '<td></td>';
                                                            dts[j].cat_description      !== null    || dts[j].cat_description   !== undefined ? vHtml += '<td>' + dts[j].doc_description + '</td>': vHtml += '<td></td>';
                                                            
                                                            vFileExt == 'pdf' ?  vHtml += '<td class="center-align"><span class="badge red" style="color:white;">' + vFileExt + '</span></td>': vHtml += '<td class="center-align"><span class="badge blue" style="color:white;">' + vFileExt + '</span></td>'; 

                                                            vHtml += '<td><a class="waves-effect waves-light btn center-align"  data-id="'+ dts[j].doc_id +'" id="btn-edit"     style="background-color:#f3bf3d; width:155px;"><i class="material-icons right">mode_edit</i>Edit</a></td>';
                                                            vHtml += '<td><a class="waves-effect waves-light btn center-align"  data-id="'+ dts[j].doc_id +'" id="btn-delete"   style="background-color:#d43c37; width:155px;"><i class="material-icons right">delete</i>Delete</a></td>';
                                                            vHtml += '<td></td>';
                                                            
                                                        vHtml += '</tr>';
                                                    });

                                                vHtml += '</tbody>';
                                            vHtml += '</table>';
                                        vHtml += '</div>';
                                    }
                                }
                            });

                        vHtml += '</div>';
                    });

                    /* Show the HTML. */
                    $('#div-list-docs').append(vHtml);
                }

            },complete: function(xhr){

                /* Remove de Cursor. */ 
                $('#div-cursor').slideUp('slow');
            }   
        });
    }FListDocuments(1);

Ele me retorna as Tables, mais como voce pode ver eu tenho que fazer um select dentro do outro pois quero primeiro criar um cabecalho para depois mostrar os itens que pertencem a esta categoria.

Fui claro a respeito ?

Na verdade quero fazer o mesmo processo com Ajax mais sem ter que realizar duas requisicoes no mesmo codigo ?

Muitissimo Obrigado um abraco a todos.

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.