不能从多对多关系访问模型


Cannot access model from many to many relation

我正在使用Laravel。我试图将用户模型和消息模型与多对多关系联系起来。当我访问用户消息时,它说函数未定义。但是这个函数是有定义的。这是我得到的错误

 Call to undefined method Illuminate'Database'Eloquent'Collection::messages()

用户模型。

  public function docs(){
    return $this->belongsToMany('Doc');
  } 
  public function messages(){
    return $this->belongsToMany('Message');
  } 

消息模型。

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

我正在尝试为选定的用户存储消息。这就是误差产生的地方。我还设置了数据透视表。

消息控制器。

public function store()
{
    //
    $input = Input::only('title', 'body', 'sel_users');
    $msg = Input::only('title', 'body');
    $sel_users = Input::only('sel_users');
    $this->messageForm->validate($input);
    $insert = Message::create($msg);
    $id = $insert['id'];
    foreach ($sel_users as $userid) {
        $user = User::find($userid);
        $user->messages()->attach($id);
    }
    return Redirect::route('messages.index');
}

您的问题是循环中的userid是一个数组,而不是单个id:

foreach ($sel_users as $userid) {
    $user = User::find($userid);  // find() provided with array returns collection...
    $user->messages()->attach($id);  // .. so here you can't call messages() on that collection
}
// it works the same as:
// User::whereIn('id', $userid)->get();

这是因为Input::only(...)返回数组,并且您必须在sel_users中也有一个id数组,因此:

$sel_users = Input::only('sel_users');
// $sel_users = array('sel_users' => array( id1, id2 ...) )

你想要的是:

$sel_users = Input::get('sel_users');
// $sel_users = array( id1, id2 ...)