Laravel Relationship error trying to call a relationship within the model

好久不见. 提交于 2019-12-11 09:05:01

问题


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;
} 

My function userLink gives me the error : 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?

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');
    }
}

回答1:


Try this instead:

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

or this:

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

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

Then:

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

Also check the Defining An Accessor.

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

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


来源:https://stackoverflow.com/questions/23977519/laravel-relationship-error-trying-to-call-a-relationship-within-the-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!