How to filter a pivot table using Eloquent?

前端 未结 3 878
情话喂你
情话喂你 2021-02-05 01:54

I\'m using a pivot table on the project I\'m working with to get works of users.

E.g: User::find(1)->works gives me the works of user with ID of 1.

3条回答
  •  Happy的楠姐
    2021-02-05 02:35

    I try to setup all relationships in both directions as this allows for use of dynamic properties, eg $user->works().

    class Collection extends Eloquent {
        public function contents()
        {
            return $this->belongsToMany('Content', 'collection_content', 'collection_id', 'content_id')->withPivot('collection_id', 'group_id', 'field_identifier');
        }
    }
    
    class Content extends Eloquent {
        public function collections()
        {
            return $this->belongsToMany('Collection', 'collection_content', 'collection_id', 'content_id')->withPivot('collection_id', 'group_id', 'field_identifier');
        }
    }
    
    class CollectionContent extends Eloquent {
        public function content()
        {
            return $this->belongsTo('Content');
        }
    
        public function collection()
        {
            return $this->belongsTo('Collection');
        }
    }
    

    Then query:

    $works = User::find(1)->works()->where('active', 1)->get();
    

    Eloquent's documentation is awful when it comes to the use of pivot tables. This is a great tutorial: http://www.developed.be/2013/08/30/laravel-4-pivot-table-example-attach-and-detach/

提交回复
热议问题