【问题标题】:Using Laravel, how can I retrieve records through a pivot table?使用 Laravel,我如何通过数据透视表检索记录?
【发布时间】: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 方法,因此出现错误消息。请参阅下面的答案。
  • 你好。我已经看到并添加了它。请看我下面的回复。查询返回包含用户的集合,但我不知道返回它们的正确语法。

标签: php laravel


【解决方案1】:
class User extends Model
{
   public function scopeGender($query){
       return $query->where('gender', 'f');
   }
}

使用查询范围
一旦定义了范围,您就可以在查询模型时调用范围方法。但是,调用方法时不需要包含范围前缀。您甚至可以将调用链接到各种范围,例如:

$users = App\User::gender()->get() or -> first(); //<-- notice that you still need to 
chain get or first to fetch results.

这是您在查询中遇到的一个错误。您的查询应如下所示。

 $the_group = Group::with('users')->Name($query) -> get();   
 //returns all rows. use a foreach loop.


 $the_group = Group::with('users')->Name($query) -> first(); 
 // returns first

 echo $the_group -> users;

希望对您有所帮助。

【讨论】:

  • 谢谢 - 我试过你的版本,但我仍然遇到同样的问题。未定义属性:Illuminate\Database\Eloquent\Collection::$users
  • 当我使用你的查询和 dd($the_group);我可以向下钻取并找到集合中的用户。它只是不接受我给用户的电话......不知道如何继续。有什么想法吗?好像很近了。
  • @EdFearon 您正在使用 get 并且它返回所有行,因此您必须一次循环遍历数组,或者您只想先使用单行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
  • 2019-04-27
  • 2019-03-20
  • 2019-08-19
  • 1970-01-01
  • 1970-01-01
  • 2021-01-22
相关资源
最近更新 更多