简体   繁体   English

Laravel一对一关系出现错误

[英]Laravel one-to-one relationship giving errors

Im trying to implement a one-to-one relationship, im calling it from a 'command' and i keep getting a Undefined property error when viewing any record in that relationship. 我试图实现一对一的关系,我从一个“命令”调用它,并且在查看该关系中的任何记录时,我总是收到未定义的属性错误。

In my model i have the following 在我的模型中,我有以下内容

public function preferences()
{
    return $this->hasOne('App\WebsitePreferences', 'id', 'website_id');
}

Then im calling it as such 然后我这样称呼它

    $websites = Website::where('active', 1)->get();

    foreach ($websites as $website) {

        var_dump($website->preferences()->status);

    }

the exact error is as follows 确切的错误如下

Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$status 

If i do a var_dump($website) it returns all the values in that table, just not the ones in the WebsitePreferences table associated with that 'Website' 如果我执行var_dump($ website),它将返回该表中的所有值,而不是与该“网站”相关联的WebsitePreferences表中的所有值

I have a few other one-to-one relationships and they all work just fine. 我还有一些其他的一对一关系,它们都很好。

Any help would be greatly appreciated. 任何帮助将不胜感激。

When you call a relationship as a method, it returns the QueryBuilder instance. 当您将关系作为方法调用时,它将返回QueryBuilder实例。 This allow you to keep chaining with where, with and so on. 这使您可以与where,with等保持链接。

Instead you should call it as an attribute: 相反,您应该将其称为属性:

$website->preferences->status 

In your model try this: 在您的模型中尝试以下操作:

public function preferences()
{
    return $this->hasOne('App\WebsitePreferences', 'website_id');
}

In your controller: 在您的控制器中:

Website::with('preferences')->get()

in your view: 在您看来:

 foreach ($websites as $website) {
     @php(dd($website->preferences->status)); }
public function preferences()
{
    return $this->hasOne('App\WebsitePreferences', 'id', 'website_id');
}


$websites = Website::where('active', 1)->get();

You need to check empty for relation 您需要检查关联是否为空

foreach ($websites as $website) {
     if(empty($website->preferences) === false){
       $website->preferences->status
    }
}

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

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