【问题标题】:Cannot access model from many to many relation无法从多对多关系访问模型
【发布时间】:2014-07-01 13:27:27
【问题描述】:

我正在使用 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');

}

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    您的问题是循环中的 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 ...)
    

    然后您的其余代码将按预期工作。

    【讨论】:

    • 工作就像一个魅力。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 2014-02-02
    • 1970-01-01
    相关资源
    最近更新 更多