【问题标题】:Get relation data when search in laravel在laravel中搜索时获取关系数据
【发布时间】:2018-04-29 11:28:31
【问题描述】:

我有 laravel 5.6 项目 这是我的模型代码

public function getClassTreaner()
{
    return $this->hasOne('App\User', 'id', 'class_treaner');
}

public static function searchScoop($keyword)
{
    $data = Classe::where('id','like','%'.$keyword.'%')
        ->orWhere('class_name','like','%'.$keyword.'%')
        ->limit(30)
        ->get();

    return $data;
}

现在当我在 js 代码中使用 Searchscoop 时,它看起来像这样:

$.ajax({
  type:'POST',
  url: path+'classsearch',
  data: {data:this.message},
  success:(data) => {
    if(data.length >= 1)
    {
      for(i = 0;i<data.length;i++)
      {
        this.arrayresults.push({id:data[i]['id'],class_name:data[i]['class_name'],class_start_time:data[i]['class_start_time'],class_end_time:data[i]['class_end_time'],class_date:data[i]['class_date'],class_treaner:data[i]['get_class_treaner']})
      }
      this.ok = true;
    }
    else
    {
      this.ok = false;
      this.noresult = true;
    }
   },
  error:function()
  {
    console.log("error");
  }
});

在这一行:

this.arrayresults.push({id:data[i]['id'],class_name:data[i]['class_name'],class_start_time:data[i]['class_start_time'],class_end_time:data[i]['class_end_time'],class_date:data[i]['class_date'],class_treaner:data[i]['get_class_treaner']})

最后结果get_class_treaner我无法访问模型关系视图ajax。

我尝试写名字getClassTreaner,但是我无法访问ajax中的模型数据。

【问题讨论】:

  • 在 ajax 的成功功能中尝试控制台记录数据(响应)并查看您从后端得到的结果。然后发布它以查看问题所在
  • 没有空白数据
  • 所以问题出在你的后端。在 laravel 中,将 return $data 替换为:return response->json($data)

标签: javascript php laravel vue.js laravel-5.6


【解决方案1】:

如果你在后端加载它,你只能在你的前端访问一个关系:

$data = Classe::where('id','like','%'.$keyword.'%')
    ->orWhere('class_name','like','%'.$keyword.'%')
    ->limit(30)
    ->with('getClassTreaner')
    ->get();

【讨论】:

  • 你写的data是空的。
猜你喜欢
  • 1970-01-01
  • 2019-11-23
  • 1970-01-01
  • 2021-10-25
  • 2017-12-13
  • 2021-10-22
  • 2015-10-30
  • 2015-06-11
  • 1970-01-01
相关资源
最近更新 更多