Laravel:belongsTo() 关系假设一对多关系而不是一对一

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17610822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:07:46  来源:igfitidea点击:

Laravel: belongsTo() relation assume one-to-many relationship instead of one-to-one

phpormlaravel

提问by Ingro

I'm having a tedious problem with Laravel's ORM.

我在 Laravel 的 ORM 上遇到了一个乏味的问题。

I have a model with multiple relationships, like this:

我有一个具有多种关系的模型,如下所示:

class Pages extends Eloquent {

    protected $guarded = array('id','config_id');

    public function template()
    {
        return $this->belongsTo('Templates', 'templates_id');
    }

    public function updateUser()
    {
        return $this->belongsTo('Users', 'updated_by');
    }

Now I can access the template related item in a simple way, like this:

现在我可以通过一种简单的方式访问模板相关的项目,如下所示:

$this->template->name;

And it works out of the bat, because Laravel's ORM assumes it is a one-to-one relationship and internally calls the first() method.

它立即生效,因为 Laravel 的 ORM 假定它是一对一的关系并在内部调用 first() 方法。

But when I try the same with updateUser it fails, returning an error, saying that it can't call name on a non-object.

但是当我对 updateUser 尝试同样的操作时它失败了,返回一个错误,说它不能在非对象上调用 name。

But if I try this:

但如果我试试这个:

$this->updateUser()->first()->name;

it works, but it doesn't feel right to me.

它有效,但对我来说感觉不对。

So my question is, how Laravel's ORM decide if a relationship defined with belongsTo() is one-to-one or one-to-many? Is there a way to force a needed behaviour?

所以我的问题是,Laravel 的 ORM 如何决定使用belongsTo() 定义的关系是一对一还是一对多?有没有办法强制需要的行为?

Thanks

谢谢

采纳答案by Laurence

You need to define the relationship. You can define 'different' relationships on the perspective.

您需要定义关系。您可以在视角上定义“不同”的关系。

The ->belongsTo()function is an inverse function - but you havent defined anything on the users table - so it is wrongly assuming the inverse is one-to-many.

->belongsTo()函数是一个反函数——但你没有在用户表上定义任何东西——所以它错误地假设反函数是一对多的。

Just add this to your users class:

只需将此添加到您的用户类:

class Users extends Eloquent {

    public function pages()
    {
        return $this->hasMany('Pages');
    }
}