如何使用 AJAX 和 Laravel 显示 2 个表中的数据?

瑞安·萨克斯

我使用 AJAX 创建了实时搜索,用户可以在其中搜索工作以及它从我的employer_profiles表中返回数据的位置,特别是 2 列company_namecompany_address. 我有一个名为job_posts2 列job_titlejob_description. 当他们希望雇用某人时,登录的雇主可以在这里为他们的公司创造就业机会。当然这里有关系,两个表都有一个 user_id 列。

我想在我的表中显示 3 列,company_name以及company_address来自employer_profiles表和job_title来自job_posts表。

是否有 JOIN 会有所帮助?如果是,我该怎么做?这是我仅从employer_profiles表中获取的代码

AdminJobSeekerSearchController.php:

public function action(Request $request)
{
    if($request->ajax()){
        $output = '';

        $query = $request->get('query');
        if($query != ''){
            $data = DB::table('employer_profiles')
                ->where('company_name', 'like', '%'.$query.'%')
                ->orWhere('company_address', 'like', '%'.$query.'%')
                ->get();
        }else{
            $data = DB::table('employer_profiles')
                ->orderBy('id', 'desc')
                ->get();
        }

        $total_row = $data->count();

        if($total_row > 0){
            foreach($data as $row){
                $output .= '
                <tr>
                    <td>'.$row->company_name.'</td>
                    <td>'.$row->company_address.'</td>
                    <td><a type="button" href="/admin/job-seeker/search/employer/'.$row->id.'" class="btn btn-primary">View</a></td>
                </tr>
                ';
            }
        }else{
            $output = '
            <tr>
                <td colspan="5">No Data Found</td>
            </tr>
            ';
        }
        $data = array(
            'table_data' => $output,
            'total_data' => $total_row
        );
        return response()->json($data);
    }
}

index.blade:

@extends('layouts.admin')

@section('content')

    @if (session('send-profile'))
        <div class="alert alert-success">
            {{ session('account') }}
        </div>
    @endif

    <div class="row">

        <div class="col-md-12">
            <!-- Topbar Search -->
            <form class="navbar-search">
                <div class="input-group">
                    <input type="text" class="form-control bg-lightblue border-0 small text-white border-dark" name="search" id="search" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2">
                    <div class="input-group-append">
                        <button class="btn btn-success" type="button">
                            <i class="fas fa-cannabis"></i>
                        </button>
                    </div>
                </div>
            </form><br>
        </div>

        <div class="col-md-12">

            <table class="table table-hover table-responsive-sm">
                <thead class="thead-dark">
                <tr class="align-items-center"><th colspan="4" style="text-align: center;"><h5><strong>Total Results: <span id="total_records"></span></strong></h5></th></tr>
                <tr>
                    <th scope="col">Company Name</th>
                    <th scope="col">Immediate Contact</th>
                    <th scope="col">Address</th>
                    <th scope="col"></th>
                </tr>
                </thead>
                <tbody>



                </tbody>
            </table>

        </div>

    </div>

    {{-- Show Pagination --}}
    <div class="row">
        <div class="col-md-6 offset-md-3 d-flex justify-content-center">

            {{$employerProfiles->render()}}

        </div>
    </div>

@stop

@push('scripts')
    <script>

        $(document).ready(function() {

            fetch_customer_data();

            function fetch_customer_data(query = '')
            {

                $.ajax({
                    url:"{{ route('admin.job.seeker.search.action') }}",
                    method: 'GET',
                    data: {query:query},
                    dataType:'json',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    success:function(data)
                    {
                        $('tbody').html(data.table_data);
                        $('#total_records').text(data.total_data);
                    }
                })

            }

            $(document).on('keyup', '#search', function(){
                var query = $(this).val();
                fetch_customer_data(query);
            })

        });

    </script>
@endpush

网页.php

Route::get('/admin/job-seeker/search/action', 'AdminJobSeekerSearchController@action')->name('admin.job.seeker.search.action')->middleware('verified');
ryantxr

希望这足以让您了解如何做到这一点。

注意:您的控制器正在尝试输出 json,但您的输出字符串是 html。

假设这些表:

CREATE TABLE `employer_profiles` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `company_name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `company_address` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 
COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `job_posts` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `employer_profile_id` int(10) unsigned NOT NULL,
  `description` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

这是一些数据

INSERT INTO `employer_profiles` (`id`, `company_name`, `company_address`, `created_at`, `updated_at`)
VALUES
(1, 'Bolay', '123 main street', '2020-03-29 07:18:30', '2020-03-29 07:18:30'),
(2, 'Barones Pizza', '345 Sample road', '2020-03-29 07:18:56', '2020-03-29 07:18:56'),
(3, 'Sigma Electronics', '34 Yamato Road', '2020-03-29 07:23:21', '2020-03-29 07:23:21');

工作:

INSERT INTO `job_posts` (`id`, `employer_profile_id`, `description`, `created_at`, `updated_at`)
VALUES
(1, 1, 'Cashier', '2020-03-29 07:20:18', '2020-03-29 07:20:23'),
(2, 1, 'Food prep', '2020-03-29 07:20:35', '2020-03-29 07:20:35'),
(3, 2, 'Chef', '2020-03-29 07:23:41', '2020-03-29 07:23:41'),
(4, 3, 'QA engineer', '2020-03-29 07:24:00', '2020-03-29 07:24:00');

使用 DB Facade 的典型代码:

$data = DB::table('employer_profiles')
        ->join('job_posts', 'job_posts.employer_profile_id', '=', 'employer_profiles.id')
        ->get();
    foreach($data as $row){
        echo json_encode($row) . "\n";
    }

使用雄辩

雇主档案.php

namespace App;
use Illuminate\Database\Eloquent\Model;

class EmployerProfile extends Model
{
    public function jobposts()
    {
        return $this->hasMany('App\JobPost');
    }
}

招聘信息.php

namespace App;
use Illuminate\Database\Eloquent\Model;

class JobPost extends Model
{
    //
}

然后,通常您可以使用此代码。这个特定的代码片段是在 Laravel 命令中运行的。您可以将其视为可以在任何地方使用的代码。

use App\JobPost;
use App\EmployerProfile;

    $all = EmployerProfile::all();
    foreach($all as $emp) {
        $this->line($emp->company_name);
        foreach($emp->jobposts as $post) {
            $this->line('   ' . $post->description);
        }
    }

控制器:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\EmployerProfile;

class EmployerController extends Controller
{
    public function index()
    {
        $all = EmployerProfile::all();
        $output = [];
        foreach($all as $emp) {
            foreach($emp->jobposts as $post) {
                $output[] = [
                    'company_name' => $emp->company_name,
                    'company_address' => $emp->company_address,
                    'description' => $post->description
                ];
            }
        }
        // output json
        return response()->json($output);
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Laravel显示2个表中的数据

使用ajax,jquery和symfony2在表中显示数组数据

在laravel中,如何使用2个输入字段“ id”和“加入日期”在视图中搜索和显示学生数据

使用ajax和Symfony2显示数据

如何使用mysql从3个表中显示2个值和1个值

如何使用laravel eloquent从其他表中获取和显示数据

如何在 laravel 中基于 2 个主键显示数据?

使用2个不同的数据在图表中显示laravel

如何在sql中仅显示2个表中的当前和有效数据

在 Laravel 中使用 Ajax 显示数据

从xml文件中获取数据并使用Ajax和xpath在html表中显示

如何通过 Ajax 检索记录并在表 Laravel 中显示

如何使用laravel模型中的hasOne关系从2个表中获取数据中的数据

使用ajax在表中显示数组数据

如何在jQuery中对laravel和ajax分别使用

Laravel AJAX搜索和显示帖子

在选择ajax和laravel上显示div

如何在yii2中使用来自两个表的显示数据

从使用数据透视表连接的2个表中获取数据(Laravel 5.3)

如何使用 JQUERY AJAX 和 HTML 每 30 秒从 XML 读取和显示数据

如何在Laravel中使用外键从2个表中返回数据

Laravel 查询以使用另一个表和输入从表中获取数据

如何使用Laravel,Bootstrap Modal和Ajax将数据发布并插入到DB中

如何使用AJAX和LARAVEL在MySQL中插入数据而不刷新页面

如何在laravel中基于Auth用户显示来自另一个表的数据

在Laravel和Eloquent中获取2个以上联接表的数据

如何在WordPress中使用Ajax使用php和Json显示数据库列

如何使用ajax在select2中显示多个结果数据?

使用jquery ajax如何显示显示到表中的搜索数据