dskld5423 2017-09-15 13: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 14: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部