首页 > 解决方案 > 使用 ajax 和 laravel 获取数据

问题描述

 public function show_offers(Request $request){
                if($request->ajax()){
                    $all_jobs=Job_offer::all();
                    return response()->json($all_jobs);       
                 }
            }

我有控制器以 json 格式返回 all_jobs。在我的 html 中,我想在 all_jobs 变量中显示与 catagory_id 相关的类别名称我已经尝试过,但它只返回 category_id=9 希望我想显示与相关的类别名称

 <script> 
      $(document).on('keyup','.form-control',function(){
        var root = "job_listing";
        $.ajax({
          url: root,      
          method: 'GET',
          dataType:'json',
          success:function(response){

            for (var i = 0; i < response.length; i++){
                console.log(response[i].category_id)  
                $('.job').html(response[i].offer_title);
                $('.location').html(response[i].location_id);

                }

          }

        })
      });
    </script>

工作机会表结构

public function up()
    {
        Schema::create('job_offer', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('employer_id');
            $table->unsignedBigInteger('category_id');
            $table->unsignedBigInteger('location_id');
            $table->unsignedBigInteger('salary_id');
            $table->unsignedBigInteger('experience_id');


            $table->foreign('employer_id')->references('id')->on('employers')->onDelete('cascade')->onUpdate('cascade');;
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade')->onUpdate('cascade');;
            $table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade')->onUpdate('cascade');;
            $table->foreign('salary_id')->references('id')->on('salaries')->onDelete('cascade')->onUpdate('cascade');;
            $table->foreign('experience_id')->references('id')->on('experience')->onDelete('cascade')->onUpdate('cascade');;

            $table->string('offer_title');
            $table->string('description');
            $table->string('type_emploi');
            $table->string('offer_image');
            $table->boolean('status')->default(false);
            $table->timestamps();
        });
    }

标签: ajaxlaraveleloquent

解决方案


在您的 JobOffer.php 模型文件中添加此代码

public function category()
{
    return $this->belongsTo(Categories::class, 'category_id');
}

然后在您的控制器中尝试以下代码:

$all_jobs=Job_offer::with('category')->all();

然后在 Ajax 中尝试访问此数据将获得您的类别名称:

response[i].category.name

这里的名称是您的类别表的字段名称,其中包含类别的名称。


推荐阅读