试图在模型中调用关系的Laravel Relationship错误 [英] Laravel Relationship error trying to call a relationship within the model

查看:442
本文介绍了试图在模型中调用关系的Laravel Relationship错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Laravel"4.1.x-dev"上,

On Laravel "4.1.x-dev",

如何在模型中的关系上调用方法?在下面的示例中

How can I call a method on a relation within the model? From the below example

public function userLink() {
  return $this->user->link;
} 

我的函数userLink给我错误:Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

我还有另一种方法可以通过某种急切的加载技巧从绘图中访问链接的用户吗?

Also is there another way for me to access the linked user from Drawing with some kind of eager loading trick?

我有几种不同类型的用户.每种类型的用户都有自己的表,每个表中的 ID users 表的* ID **相对应.在我的Users模型中,我有一个名为"link"的方法,该方法执行"morphTo"并获取正确的用户对象.

I have several different type of users. Each type of user has it's own table with an ID in each table that corresponds to the *ID** of the users table. In my Users model I have a method called ''link'' that performs a ''morphTo'' and gets me the correct user object.

class Drawing extends Eloquent {
    public function user() {
        return $this->belongsTo('User', 'user_id');
    }

    // this throws the relation error above, also I beleive this does two queries, anyway to improve this?
    public function userLink() {
        return $this->user->link;
    }
}

class User extends Eloquent {
    public function link() {
        return $this->morphTo('User', 'type', 'id');
    }
}

class Retailer extends Eloquent {
    public function user() {
        return $this->belongsTo('User', 'id');
    }
}

class Manufacturer extends Eloquent {
    public function user() {
        return $this->belongsTo('User', 'id');
    }
}

推荐答案

尝试以下方法:

Drawing::first()->user->link;

或者这个:

// Drawing model
public function user()
{
    return $this->belongsTo('User', 'user_id');
}

// Drawing model
// Requires above relation
public function userLink()
{
    return $this->user->link;
}

然后:

$ulink = Drawing::first()->userLink();

还请检查定义访问器.

更新:只需对您的方法进行如下更改(创建accessor):

Update: Just make changes to your method like this (Create an accessor):

public function getUserLinkAttribute()
{
    return $this->user->link;
}

这篇关于试图在模型中调用关系的Laravel Relationship错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆