dskld5423 2017-09-15 21:53
浏览 63
已采纳

Laravel | 雄辩地填充外国数据

I have a database which is set out with a news and a news categories tables.

I have news which has a category 1 which links to a foreign key of the categories table where the category value equals the id in the categories table.

I'm trying to make a controller that gets the category name rather than the category ID when returning the results as a JSON response.

So far I have this inside of a model:

public function category()
{
    return $this->belongsTo(NewsCategories::class);
}

And then I'm doing this inside of a controller:

public function index()
{
    $news = new News();
    $news = $news->category()->get();

    return response()->json(['data' => $news], 200);
}

But the JSON response that gets returned is empty. I have googled some things but haven't really found anything useful regarding getting the foreign field which is title within the categories table.

This is the response that I get

{
  data: [ ]
}
  • 写回答

1条回答 默认 最新

  • duanhuan8983 2017-09-15 22:15
    关注

    The first issue is that you're under the impression that your new News instance has linked categories:

    $news = new News();
    

    This will yield just an empty model instance; it has no database representation yet. Try fetching categories through a populated model instance:

    $news = News::first();
    
    // Or:
    $news = News::find(1);
    

    and retry the JSON response.

    Second issue is that by calling $news->category()->get() you're actually querying the relation. If you only need to access the title, try $news->category->title which will load the associated category record and access the title field for you.


    Regarding your comment, read on eager/lazy loading.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看