Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rjrocks's avatar

Retrieving records with _____________ relationship ?

I have 5 tables.

  1. User tabel => This table stores the data of users.
  2. Exam table => This table stores the data of exams.
  3. Feeds table => This table stores the data of feeds.
  4. Exam_User_Pivot table => This table stores the data of users and exams means the user_id and exam_id.
  5. Exam_Feed_Pivot table => This table stores the data of exams and feeds means the exam_id and feed_id.

Now, I want to retrieve the no. of users per each feed ?

I have three models :

1) User model

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    protected $primaryKey = 'uid';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'phone',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function exams()
    {
        return $this->belongsToMany(exam::class, 'exam_user', 'user_id', 'exam_id')->withTimeStamps();
    }
}
2) Exam model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class exam extends Model
{
    protected $primaryKey = 'eid';

    protected $fillable = [
        'exam_name',
    ];
}
3) Feed model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Feed extends Model
{
	protected $primaryKey = 'fid';

	protected $fillable = [
        'feed_type', 'title', 'description', 'feed_media', 'source',
    ];

    public function feedexams()
    {
    	return $this->belongsToMany(exam::class, 'exam_feed', 'feed_id', 'exam_id')->withTimeStamps();
    }
}

-> Users have many-to-many relationship with Exams.

-> Feeds have many-to-many relationship with Exams.

I want to retrieve the no. of users per each feed And I don't know which relationship can be use ?

0 likes
2 replies
automica's avatar

@rjrocks not related to your question but an observation.

Models should be capitalized. so you exam model should be called Exam,

Relationship on Feed should be:

Feed belongsToMany Exam:

    public function exams() // not feedexams
    {
    	return $this->belongsToMany(Exam::class, 'exam_feed', 'feed_id', 'exam_id')->withTimeStamps();
    }

also its simpler to keep primary keys as id not uid or fid. Then you don't need to define the primary keys anywhere.

Please or to participate in this conversation.