使用 Ajax - Eloquent - Laravel 一次查询两个模型

Query for two models at once with Ajax - Eloquent - Laravel

我希望能够同时列出两个模型的记录,考虑到我现在如何设置查询以将其与 Ajax 一起使用。

考虑到我的项目的其余部分 (AJAX - Laravel),现在我的查询工作正常。

public function allData(){
        $data = Siniestro::orderBy('id','DESC')->get();
        return response()->json($data);
    }

我试过这样做,但看起来我做的查询是错误的

public function allData(){
    $data = Siniestro::orderBy('id','DESC')->get();
    $users = User::all();
    return response()->json($data, $users);
}

编辑:

Esta es la vista que estoy refiriendo

这是视图;我希望通过 eloquent 查询,它显示我现在已订购(orderBy),并且它还查找与“where”匹配的字段;例如 $siniestros = Siniestro::where('estado', 'coordinado')->get();.

编辑 2

dd($users)

完整查看代码

@extends('layouts.app')

@section('content')
    <section class="section">
        <div class="section-header">
            <h3 class="page__heading">Derivar IP</h3>
        </div>
        <div class="section-body">
            <div class="row">
                <div class="col-sm-9">
                    <div class="card">
                        <div class="card-header">                          
                                Inspecciones coordinadas                        
                        </div>
                        <div class="card-body">
                            <table class="table table-sm m-1 p-1 table-bordered table-hover table-striped tablita" style="width:100%">
                                <thead>
                                    <tr>
                                        <!-- <th scope="col">#</th> -->
                                        <th scope="col">Siniestro</th>
                                        <th scope="col">Fecha IP</th>
                                        <th scope="col">Modalidad</th>
                                        <th scope="col">Dirección</th>
                                        <th scope="col">Localidad</th>
                                        <th scope="col">Inspector</th>                                    
                                        <th scope="col">Acciones</th>
                                        
                                    </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table> 
                            
                            
                        </div>
                    </div>
                </div>
                <div class="col-sm-3" style="position:fixed; bottom:550px; right:0px">
                    <div class="card">
                    <div class="card-header">                          
                                <span id="addT">Asignar IP</span>
                                <span id="updateT">Asignar IP</span>                         
                        </div>
                        <div class="card-body">
                                    

                                    <div class="col-xs-12 col-sm-12 col-md-12">
                                        <div class="form-group">
                                            <label for="inspector">Inspector</label>
                                            <input type="text" name="inspector" class="form-control"  id="inspector" for="inspector" >
                                            <span class="text-danger" id="instituteError"></span>
                                        </div>
                                    </div>


                                    <div class="col-xs-3 col-sm-3 col-md-3">
                                    <label for="inspector">Inspector</label>
                                    <select class="form-select col-xs-12 col-sm-12 col-md-12" aria-label="Default select example" for="inspector" name="inspector" >
                                            <option selected></option>
                                            
                                            <option value="Taller del asegurado">Taller del asegurado</option>
                                            
                                        </select>
                                    </div>





                                    <div class="col-xs-4 col-sm-4 col-md-4">
                                        <div class="form-group">
                                                <label for="emailperito">E-mail</label>
                                                <input type="text" name="emailperito"  class="form-control" id="emailperito" for="emailperito">
                                        </div>
                                    </div>

                                    <div class="col-xs-4 col-sm-4 col-md-4">
                                        <div class="form-group">
                                                <label for="telefonoperito">Teléfono</label>
                                                <input type="text" name="telefonoperito"  class="form-control" id="telefonoperito" for="telefonoperito">
                                        </div>
                                    </div>

                                    

                                    

                                    <input type="hidden" id="id">
                                    
                                    <button type="submit" id="updateButton" class="btn btn-primary btn-sm" onclick="updateData(event)">Asignar</button>
                                                      
                                                        
                        </div>
                        
                    </div>
                </div>
            </div>
        </div>
    </section>
    
    

@endsection


@section('javas')

  <script>
    $(document).ready(function() {
    $('.tablita').DataTable({
        "serverSide": true,
        "ajax": "/teacher/all",
        "columns": [
            // {data: 'id'},
            {data: 'siniestro'},
            {data: 'fechaip'},
            {data: 'modalidad'},
            {data: 'direccion'},
            {data: 'localidad'},
            {data: 'inspector'},
            {data: 'action', name: 'action', orderable: true, searchable: true},
            
            

            
            
        ],

        
    });
})
</script>  

<script>



    





 $('#addT').hide();
 $('#addButton').hide();
 $('#updateT').show();
 $('#updateButton').show();

$.ajaxSetup({
    headers:{
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
})

//---------------------------------------------- Llamar datos de la BD ---------------------------------------------------------------

function allData(){
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "/teacher/all",
        success: function (response){
            var data = ""
            $.each(response, function(key, value){
                data = data + "<tr>"
                // data = data + "<td>"+value.id+"</td>"
                data = data + "<td>"+value.siniestro+"</td>"
                data = data + "<td>"+value.fechaip+"</td>"
                data = data + "<td>"+value.modalidad+"</td>"
                data = data + "<td>"+value.direccion+"</td>"
                data = data + "<td>"+value.localidad+"</td>"
                data = data + "<td>"+value.inspector+"</td>"
                data = data + "<td>"
                data = data + "<button class='btn btn-info btn-sm' onclick='editData("+value.id+")'>Asignar IP</button>"
                data = data + "</td>"
                data = data + "</tr>"
            })
            $('tbody').html(data);
        }
    })
}

// --------------------------------------------- fin de llamar datos de la DB ----------------------------------------------------------

allData();

// --------------------------------------------- Limpiar los campos despues del submit -------------------------------------------------

function clearData(){
 $('#siniestro').val('');
 $('#fechaip').val('');
 $('#inspector').val('');
 $('#nameError').text('');
 $('#titleError').text('');
 $('#instituteError').text('');

}

// --------------------------------------------- fin de limpiar los campos despues del submit -------------------------------------------------

// --------------------------------------------- Agregar registros a la table de BD -------------------------------------------------


function addData(){
    var siniestro = $('#siniestro').val();
    var fechaip = $('#fechaip').val();
    var inspector = $('#inspector').val();

    $.ajax({
        type: "POST",
        dataType: "Json",
        data: {siniestro:siniestro, fechaip:fechaip, inspector:inspector},
        url:"/teacher/store/",
        success: function(data){
            allData();
            clearData();
            console.log('datos agregados con éxito');
        },

        error: function(error){
            $('#nameError').text(error.responseJSON.errors.name);
            $('#titleError').text(error.responseJSON.errors.title);
            $('#instituteError').text(error.responseJSON.errors.institute);
            
        }
    })

}

// --------------------------------------------- fin de agregar registros a la table de BD -------------------------------------------------
// --------------------------------------------- Editar registros a la table de BD ---------------------------------------------------------

function editData(id){
    



 
      $.ajax({
          type:"get",
          dataType:"json",
          url:"/teacher/edit/"+id,
          success: function(data){
             $('#addT').hide();
             $('#addButton').hide();
             $('#updateT').show();
             $('#updateButton').show();

              $('#id').val(data.id);
            //   $('#siniestro').val(data.siniestro);
            //   $('#fechaip').val(data.fechaip);
              $('#inspector').val(data.inspector);
             

              console.log(data);
          }
      })
 }

 // --------------------------------------------- Fin de editar registros a la table de BD -------------------------------------------------
 // --------------------------------------------- Update de registros a la table de BD -----------------------------------------------------



 function updateData(event){

    event.preventDefault();
     var id = $('#id').val();
    //  var siniestro =  $('#siniestro').val();
    //  var fechaip = $('#fechaip').val();
     var inspector = $('#inspector').val();

     $.ajaxSetup({
    headers:{
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
})
     

     $.ajax({
         type: "PUT",
         dataType: "json",
         data: {inspector:inspector},
         url: "/teacher/update/"+id,
         success: function(response){
            allData();
            clearData();
         console.log('Siniestro asignado con éxito');
         }
         
     })


 }

 


</script>
@endsection

编辑 3

enter image description here

看,之前显示属性的捕获仅来自 $users,现在使用 $data = Siniestro::orderBy('fechaip','ASC')->get(); $users = User::all();$combo = ['users' => $users, 'data' => $data];dd($combo);如您所见,它向我显示了所有用户,但我看不到他们的“属性”,很奇怪,对吧?会不会有问题?

json 通常总是 post 一个数组,你不能 post 这样的单个对象。您需要将对象转换为数组并 post 它。

$response_array['message'] = $data;
                $response_array['data'] = $users;
                return response()->json($response_array);

$data = ['users' => $users, 'content' => $contents]; return 响应()->json($data);

您可以使用以下方式接收这些数据:

success: function(response) {
console.log(response.content);
}

所以当你这样做时

$data = Siniestro::orderBy('fechaip','ASC')->get();
$users = User::all();
$combo = ['users' => $users, 'data' => $data];

return response()->json($combo);

然后您应该检查 javascript 中的传入响应数据。现在数据由 datausers 键控。因此,在 javascript 中的 allData() 函数中,您必须根据按键进行调整以显示数据。

function allData(){
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "/teacher/all",
        success: function (response){

            //Here console.log(response) to see the structure of incoming data
            console.log(response)
            // Should output something like
            // {users: [... array of user records(objects)], data: [... array of siniestro records (objects)}
           
            // So to generate the display markup you may have to do
            $siniestroMarkup = "";
            $.each(response.data, function(key, value){
                siniestroMarkup = siniestroMarkup + "<tr>"
                siniestroMarkup = siniestroMarkup + "<td>"+value.id+"</td>"
                siniestroMarkup = siniestroMarkup + "<td>"+value.siniestro+"</td>"
                siniestroMarkup = siniestroMarkup + "<td>"+value.fechaip+"</td>"
                siniestroMarkup = siniestroMarkup + "<td>"+value.modalidad+"</td>"
                siniestroMarkup = siniestroMarkup + "<td>"+value.direccion+"</td>"
                siniestroMarkup = siniestroMarkup + "<td>"+value.localidad+"</td>"
                siniestroMarkup = siniestroMarkup + "<td>"+value.inspector+"</td>"
                siniestroMarkup = siniestroMarkup + "<td>"
                siniestroMarkup = siniestroMarkup + "<td>"
                siniestroMarkup = siniestroMarkup + "<button class='btn btn-info btn-sm' onclick='editData("+value.id+")'>Asignar IP</button>"
                siniestroMarkup = siniestroMarkup + "</td>"
                siniestroMarkup = siniestroMarkup + "</tr>"
            })
            $('tbody').html(siniestroMarkup);
        });

            // Similarly you can access the user records
         $.each(response.users, function(key, value) {
            //Here value will represent each user record
         });

}

并且您可能还需要调整 DataTable ajax 响应,如果您正在使用它可能如下所示(检查确切的响应数据结构以及如何访问 DataTable)

$(document).ready(function() {
    $('.tablita').DataTable({
        "serverSide": true,
        "ajax": "/teacher/all",
        "columns": [
            // {data: 'id'},
            {data: 'data.siniestro'},
            {data: 'data.fechaip'},
            {data: 'data.modalidad'},
            {data: 'data.direccion'},
            {data: 'data.localidad'},
            {data: 'data.inspector'},
            {data: 'data.action', name: 'action', orderable: true, searchable: true},              
        ],
    });
})

检查上面的内容,看看这是否是您想要的数据。