jeudi 31 mai 2018

Laravel fetch only pivot columns in many to many relationship

I have a User model that relates to a Section model through a pivot model UserTrainingSection. I have a pivot table that stores the foreign keys for both tables called section_user.

I have 2 additional pivot table columns called completed and completed_date.

The problem I am having is that when I fetch my data it returns all the columns from the User model along with the additional pivot columns.

    class Section extends Model
    {
        public $table = "sections";

        public $fillable = [
            'id',
            'name',
            'description',
            'parent',
            'position',
            'completion_percentage'
        ];

        public function users()
        {
            return $this->belongsToMany(User::class, 'section_user')->using('App\Models\UserTrainingSection')->withPivot('completed', 'completed_date');
        }
    }

In my API service I fetch my data like this:

Section::with(['users' => function ($q) {
                $q->where('users.id', Auth::user()->id);
            }])->first();

How do I only return the pivot table columns and exclude the columns from the user table?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire