【发布时间】:2015-08-27 19:10:01
【问题描述】:
我有一个用户模型和一个组模型,它们通过数据透视表连接。用户可以在多个组中,组包含多个用户。
我需要检索给定组中的所有用户。到目前为止,这是我的模型和控制器代码。我将不胜感激 - 我确定我遗漏了一些明显的东西。我的错误消息取决于我尝试的内容,但使用当前代码是:
“Builder.php 第 1992 行中的 BadMethodCallException:调用未定义的方法 Illuminate\Database\Query\Builder::users()”
非常感谢!
用户:
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
//BLAH BLAH
public function groups()
{
return $this->belongsToMany('App\Group');
}
}
组:
class Group extends Model
{
protected $table = 'groups';
protected $fillable = [
'name',
'detail'
];
public function scopeName($query, $group)
{
$query->where('name', '=', $group);
}
public function users()
{
return $this->belongsToMany('App\User');
}
}
控制器代码:
public function getGroup($query)
{
// $query = "name of group" FYI
// The task of this function is to return a Datatable object containing all users in the given ($query) group
$the_group = Group::with('users')->Name($query) -> get();
dd($the_group->users);
return Datatables::of($users)->make(true);
}
【问题讨论】:
-
你有
$the_group->users,而不是$the_group->users()。你没有调用函数users(),你需要把它改成dd($the_group->users());,除非我弄错了(之前从来没有用过laravel,也许它是特定的语法) -
感谢您的回复。使用 users() 或 users()->get() 我会调用未定义的方法 Illuminate\Database\Query\Builder::users() 来代替。
-
@EdFearon 您在查询范围内缺少 get 方法,因此出现错误消息。请参阅下面的答案。
-
你好。我已经看到并添加了它。请看我下面的回复。查询返回包含用户的集合,但我不知道返回它们的正确语法。