laravel 关系方法必须返回一个 Illuminate\Database\Eloquent\Relations\Relation 类型的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23546110/
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-09 02:48:20  来源:igfitidea点击:

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

laravellaravel-4eloquent

提问by babbaggeii

Trying to get a list of users associated with an event. Here are my eloquent models:

尝试获取与事件关联的用户列表。这是我雄辩的模型:

User.php:

用户.php:

public function fbevents()
{
    $this->belongsToMany('Fbevent', 'fbevent_user');
}

Fbevent.php:

Fbevent.php:

public function users()
{
    $this->belongsToMany('User', 'fbevent_user);
}

I get this error when I try to find the list:

当我尝试查找列表时出现此错误:

$event = Fbevent::find(10);
var_dump($event->users->lists('userId'));

I've set up a pivot table in the db with the following migration:

我已经通过以下迁移在数据库中设置了一个数据透视表:

$table->increments('id');
$table->integer('fbevent_id')->unsigned()->index();
$table->foreign('fbevent_id')->references('id')->on('fbevents')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();

And added an entry in the fbevent_user table with fbevent_id = 10 and user_id = 1.

并在 fbevent_user 表中添加了一个条目,其中 fbevent_id = 10 和 user_id = 1。

回答by Razor

You need to return a result from your relations

你需要从你的关系中返回一个结果

public function fbevents()
{
    return $this->belongsToMany('Fbevent', 'fbevent_user');
}
public function users()
{
    return $this->belongsToMany('User', 'fbevent_user');
}