【问题标题】:Laravel 7 Eloquent: Comment BelongsTo User belongsToMany GroupsLaravel 7 Eloquent:评论 BelongsTo User belongsToMany Groups
【发布时间】:2020-06-26 08:40:47
【问题描述】:

我正在尝试建立以下关系:

评论 (user_id) ->belongTo 用户 ->belongsToMany ->群组

(枢轴:组用户)

我希望能够获取与评论相关联的所有组:Comment::find(i)->groups。 还有Comment::wherehas('groups')Comment::Where(groups in [1,3])

我一直在看https://github.com/staudenmeir/eloquent-has-many-deep#belongsto 但无法使其按预期工作。

 public function groups()
    {

         return $this->hasManyDeep('App\Group', ['group_user', 'App\User']);
    }

Laravel 7

【问题讨论】:

    标签: laravel eloquent has-many has-and-belongs-to-many


    【解决方案1】:

    来自 github 讨论:

    class Comment extends Model
    {
        use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
    
        public function groups()
        {
            return $this->hasManyDeep(
                Group::class
                [User::class, 'group_user'],
                ['id'],
                ['user_id']
            );
        }
    }
    

    像魅力一样工作!

    【讨论】:

      【解决方案2】:

      这可能对你有帮助

      //'tables1','tables2','tables3' are relations in USER model & 'COL 7' is column of table 3
      
      $x=USER::where('status','active')->with('tables1','tables2','tables3')->whereHas('tables3', function($q)
                      {
                          $q->where('COL 7',"US");
      
                      })->get();
                      dd($x);
      

      【讨论】:

        猜你喜欢
        • 2018-03-08
        • 2019-05-12
        • 1970-01-01
        • 2018-08-10
        • 1970-01-01
        • 2017-02-04
        • 1970-01-01
        • 2018-08-06
        • 2015-12-22
        相关资源
        最近更新 更多