【问题标题】:data fetch with ajax and laravel使用 ajax 和 laravel 获取数据
【发布时间】:2020-07-05 23:00:39
【问题描述】:
 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();
        });
    }

【问题讨论】:

  • 请分享您的表结构
  • @Sehndev 好的,我做到了

标签: ajax laravel eloquent


【解决方案1】:

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

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

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

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

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

response[i].category.name

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

【讨论】:

  • 谢谢它与 $all_jobs=Job_offer::with('category')->get(); 配合得很好
  • @MoussaEloifi 很高兴为您提供帮助,如果此答案解决了您的问题,请单击答案旁边的复选标记将其标记为已接受。请参阅:How does accepting an answer work? 了解更多信息
猜你喜欢
  • 2018-03-18
  • 2020-11-16
  • 1970-01-01
  • 2018-02-11
  • 1970-01-01
  • 1970-01-01
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多