【问题标题】:Laravel attach() method not working to hasMany sideLaravel attach() 方法不适用于 hasMany 方面
【发布时间】:2014-03-01 06:16:43
【问题描述】:

应用程序具有模型:

Atividade.php

class Atividade extends Eloquent {
    public function intervencoes() {
        return $this->belongsToMany('Intervencao');
    }
}


Intervencao.php

class Intervencao extends Eloquent {
    public function atividades() {
        return $this->hasMany('Atividade');
    }
}


以下代码有效:

Atividade::find($id)->intervencoes()->attach($intervencao_id);

但是,这个……

Intervencao::find($id)->atividades()->attach($atividade_id);

返回一个 BadMethodCallException:

调用未定义的方法 Illuminate\Database\Query\Builder::attach()


解决方案(感谢@gnack):

我试图设置多对多关系,所以只需要更改它...

return $this->hasMany('Atividade');

到这里:

return $this->belongsToMany('Atividade');

【问题讨论】:

    标签: php laravel-4


    【解决方案1】:

    就我而言,我有两个 roles() 方法,这就是它抛出此错误的原因。

    【讨论】:

      【解决方案2】:

      查看文档 Laravel 5.7

      评论属于唯一的帖子

      class Comment extends Model
      {
          /**
           * Get the post that owns the comment.
           */
          public function post()
          {
              return $this->belongsTo('App\Post');
          }
      }
      

      一个帖子可以有多个评论

      class Post extends Model
      {
          /**
           * Get the comments for the blog post.
           */
          public function comments()
          {
              return $this->hasMany('App\Comment');
          }
      

      当你想更新/删除一个 belongsTo 关系时,你可以使用 associate/dissociate 方法。

      $post= App\Post::find(10);
      $comment= App\Comment::find(3);
      $comment->post()->associate($post); //update the model
      
      $comment->save(); //you have to call save() method
      
      //delete operation
      $comment->post()->dissociate(); 
      
      $comment->save(); //save() method
      

      【讨论】:

        【解决方案3】:

        在此处查看 Laravel 文档: http://laravel.com/docs/eloquent#inserting-related-models

        基本上,您已经为相同的两个表设置了两种不同类型的关系 - 您设置了多对多和一对多。看起来您可能想要多对多,因此您需要更改此行:

        return $this->hasMany('Atividade');
        

        到这里:

        return $this->belongsToMany('Atividade');
        

        这会将关系设置为多对多关系,然后将支持attach() 方法。

        attach() 方法仅适用于多对多,对于其他关系,有 save()saveMany()associate()(请参阅上面链接的文档)。

        【讨论】:

        • 是的,我很困惑。谢谢!
        【解决方案4】:

        attach() 用于多对多关系。看来您的关系应该是多对多的,但您没有为此正确设置。

        class Intervencao extends Eloquent {
            public function atividades() {
                return $this->belongsToMany('Atividade');
            }
        }
        

        那么attach() 应该可以工作

        【讨论】:

          猜你喜欢
          • 2016-04-06
          • 2018-03-29
          • 2018-12-28
          • 2018-04-22
          • 1970-01-01
          • 2023-03-24
          • 2018-09-18
          • 1970-01-01
          • 2018-10-30
          相关资源
          最近更新 更多