简体   繁体   English

Laravel关系返回null

[英]Laravel relationship returning null

I'm trying to fetch database data through a model relationship in Laravel. 我正在尝试通过Laravel中的模型关系来获取数据库数据。 I've set up one model, like this: 我建立了一个模型,像这样:

<?php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class Userskeywords extends Eloquent {

    public function relatedKeywords()
    {
        return $this->hasOne('Keywords', 'id', 'keywordId');
    }

}
?>

And the other model is just a normal model. 而另一个模型只是普通模型。 In the database they look like this: 在数据库中,它们如下所示:

Keywords 关键词

在此处输入图片说明

UsersKeywords UsersKeywords

在此处输入图片说明

However, when I run UsersKeywords::with('relatedKeywords')->get() it returns NULL for related_keywords . 然而,当我运行UsersKeywords::with('relatedKeywords')->get()返回NULLrelated_keywords This happens when the following code is executed. 执行以下代码时,会发生这种情况。 What am I doing wrong? 我究竟做错了什么?

$keywords = Userskeywords::where('user', '=', $id)->get();
$keywords->load('relatedKeywords');
return Response::json($keywords);

Your relation is called relatedKeywords so you need to access related object with 您的关系称为relatedKeywords,因此您需要使用

$object->relatedKeywords

instead of 代替

$object->related_keywords

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM